id,node_id,number,title,user,state,locked,assignee,milestone,comments,created_at,updated_at,closed_at,author_association,active_lock_reason,draft,pull_request,body,reactions,performed_via_github_app,state_reason,repo,type 1335419018,I_kwDOAMm_X85PmOCK,6907,Subplots w/ xarrays,23484003,closed,0,,,2,2022-08-11T03:16:43Z,2022-08-11T16:21:30Z,2022-08-11T16:21:30Z,NONE,,,,"### What is your issue? I tried to add an `xarray` 1D plot to a set of subplots in a figure, but I got an error: ``` import numpy as np import xarray as xr x1 = np.linspace(0,1,10) y1 = x1**2 da1 = xr.DataArray(y1,dims=(""x""),coords={""x"":x1}) x2 = np.linspace(0,1,10,endpoint=True) y2 = np.sqrt(x2) da2 = xr.DataArray(y2,dims=(""x""),coords={""x"":x2}) fg,(ax1,ax2) = plt.subplots(nrows=2,ncols=1)#,sharex=True) da1.plot(axes=ax1) da2.plot(axes=ax2) ``` Error message: ``` Traceback (most recent call last): File ""/var/folders/g6/42nl1yms1yq8tbmt3kpgm5b80000gp/T/ipykernel_2783/171456975.py"", line 2, in da.plot(axes=ax1) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/xarray/plot/plot.py"", line 866, in __call__ return plot(self._da, **kwargs) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/xarray/plot/plot.py"", line 332, in plot return plotfunc(darray, **kwargs) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/xarray/plot/plot.py"", line 440, in line primitive = ax.plot(xplt_val, yplt_val, *args, **kwargs) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/matplotlib/axes/_axes.py"", line 1634, in plot self.add_line(line) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/matplotlib/axes/_base.py"", line 2279, in add_line self._set_artist_props(line) File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/matplotlib/axes/_base.py"", line 1105, in _set_artist_props a.axes = self File ""/Users/lucas.morton/opt/anaconda3/envs/work/lib/python3.9/site-packages/matplotlib/artist.py"", line 275, in axes raise ValueError(""Can not reset the axes. You are probably "" ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported ``` I was hoping to get to the point where I could use the `sharex=True` keyword to show data from two different `DataArrays` with incongruous `x`-coordinates. If I do this, I can make the figure, but I don't get the `sharex=True` possibility: ``` fg = plt.figure() ax1 = fg.add_subplot(211) da1.plot(axes=ax1) ax2 = fg.add_subplot(212) da2.plot(axes=ax2) ``` Interestingly, I can get the same error message if I change the order of operations here: ``` fg = plt.figure() ax1 = fg.add_subplot(211) ax2 = fg.add_subplot(212) da1.plot(axes=ax1) da2.plot(axes=ax2) ``` Any idea what might be going on here?","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/6907/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 675288247,MDU6SXNzdWU2NzUyODgyNDc=,4322,"""_center"" postfix on axis label resulting from groupby_bins persists after renaming variable",23484003,closed,0,,,5,2020-08-07T21:01:19Z,2021-01-12T16:44:49Z,2021-01-12T16:44:49Z,NONE,,,," **What happened**: I used groupby_bins + sum to reduce the resolution of my dataset along 'x' dimension. I didn't like the 'x_bins_center' label, so I renamed the x-axis dim/coord to simply 'x.' However, the ""_center"" postfix is not part of the variable name -- it appears to be some tweaking of the x-axis label when plotting. So now I am stuck with ""_center"" tagged at the end of the x-axis label, even after the units. **What you expected to happen**: It would make more sense if the '_center' were part of the variable name. That way, the name displayed on the plot is the same one that I need to access the variable in the dataset. Also, when I rename the variable, I will be able to change the way it displays. Furthermore, that will prevent the issue with ""_center"" getting pasted on after the units. **Minimal Complete Verifiable Example**: ```python import xarray as xr import numpy as np data_vars={'y':('x',np.ones((101)),{'units':'kg/m'})} coords={'x':('x',np.linspace(0,1,101,endpoint=True),{'units':'m'})} ds = xr.Dataset(data_vars,coords) dsd = ds.groupby_bins('x',np.linspace(0,1,11,endpoint=True),right=False).sum(dim='x') dsd.y.plot() #Shows that the x-axis is named ""x_bins_center"" dsd = dsd.rename({'x_bins_center':'x'}) #Fails: >ValueError: cannot rename 'x_bins_center' because it is not a variable or dimension in this dataset dsd = dsd.rename({'x_bins':'x'}) #Succeeds, b/c the variable is ACTUALLY named 'x_bins' dsd.x.attrs['units']='m' dsd.y.plot() #x-axis label is ""x [m]_center"" -- there's a sneaky renaming thing that is appending _center to the end of the label ``` **Anything else we need to know?**:
Plots Here's the 1st plot showing the default x-axis label prior to renaming: ![Original_plot](https://user-images.githubusercontent.com/23484003/89687789-aa88e580-d8b5-11ea-9553-a497eff5f238.png) Here's the 2nd plot showing the mangled x-axis label after I renamed the variable & reestablished the units: ![Butchered_plot](https://user-images.githubusercontent.com/23484003/89687915-efad1780-d8b5-11ea-9348-f7016325e377.png)
**Environment**:
Output of xr.show_versions() INSTALLED VERSIONS ------------------ commit: None python: 3.7.7 (default, Mar 23 2020, 17:31:31) [Clang 4.0.1 (tags/RELEASE_401/final)] python-bits: 64 OS: Darwin OS-release: 19.6.0 machine: x86_64 processor: i386 byteorder: little LC_ALL: en_US.UTF-8 LANG: en_US.UTF-8 LOCALE: en_US.UTF-8 libhdf5: 1.10.4 libnetcdf: 4.6.1 xarray: 0.16.0 pandas: 1.0.3 numpy: 1.18.1 scipy: 1.4.1 netCDF4: 1.4.2 pydap: None h5netcdf: 0.8.0 h5py: 2.10.0 Nio: None zarr: None cftime: 1.2.1 nc_time_axis: None PseudoNetCDF: None rasterio: None cfgrib: None iris: None bottleneck: None dask: 2.20.0 distributed: None matplotlib: 3.1.3 cartopy: None seaborn: None numbagg: None pint: 0.11 setuptools: 49.2.0.post20200714 pip: 20.1.1 conda: None pytest: 5.4.1 IPython: 7.13.0 sphinx: 3.1.2
","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/4322/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 664067837,MDU6SXNzdWU2NjQwNjc4Mzc=,4255,line labels for 1D plotting,23484003,closed,0,,,2,2020-07-22T21:41:52Z,2020-07-22T21:47:42Z,2020-07-22T21:47:42Z,NONE,,,," **Is your feature request related to a problem? Please describe.** I find myself wanting to compare multiple 1D line plots. ``` d1 = xr.DataArray(np.ones((3,100)),dims=('channel','time'),coords={'channel':np.array(['a','b','c'])}) d1.sel(channel='a').plot() d1.sel(channel='b').plot() d1.sel(channel='c').plot() ``` The auto-magic labeling that happens when `_labels=True` (the default) is to place the title as `channel='a'` using the function `_title_for_slice()`. This works fine when I only want to plot one line, but if I plot sequential lines, then the title gets over-written. So, I end up doing: ``` d1.sel(channel='a').plot(label='channel=a') d1.sel(channel='b').plot(label='channel=c') d1.sel(channel='c').plot(label='channel=b') ``` which is more boiler-plate than I'd like, and prone to errors (kudos if you noticed the one I made intentionally there). **Describe the solution you'd like** Basically, I'd just like to have these two lines added to the body of `xarray.plot.line` right around line 101: ``` if _labels and not ""label"" in kwargs: kwargs[""label""] = darray._title_for_slice() ``` This would automatically add the title as a label. This would not change the way the plot looks in the original case, and if the caller of `plot` supplies a label, that will over-ride this default. **Describe alternatives you've considered** Another alternative is to make a switch in `plot` that would allow 2D arrays to be plotted as a series of 1D line plots like this, rather than as 2D heatmaps. It would be necessary to supply an indication of which of the two axes should be used as the x-axis of the plot, and which one would supply the line labels. ","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/4255/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 224878728,MDU6SXNzdWUyMjQ4Nzg3Mjg=,1388,argmin / argmax behavior doesn't match documentation,23484003,closed,0,,,11,2017-04-27T18:50:36Z,2020-07-09T21:32:52Z,2020-07-09T21:32:52Z,NONE,,,,"[The documentation](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.argmin.html) reads > Returns: > reduced : DataArray > New DataArray object with argmin applied to its data and the indicated dimension(s) removed. However, what happens is that the numpy argmin output (single index into the flattened array at which the maximum/minimum is found) is wrapped in a dummy DataArray (similar behavior for Datasets also): [In1]: x = np.linspace(0,1,5) [In2]: y = np.linspace(0,1,6) [In3]: z = np.random.randn(5,6) [In4]: example = xr.DataArray(z, {'x':x,'y':y},('x','y')) [In5]: print(example.argmin()) [Out5]: array(10) [In6]: example_ds = xr.Dataset(data_vars={'ex':example}) [In7]: print(example_ds.argmin()) [Out7]: Dimensions: () Data variables: ex int64 10 I realize that maybe for compatibility reasons it is necessary to make Datasets/DataArrays do this, but it seems like the documented behavior would be nicer. At any rate, the documentation should match the behavior. Specs: python 2.7 xarray 0.9.1 numpy 1.11.3","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/1388/reactions"", ""total_count"": 1, ""+1"": 1, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 604210297,MDU6SXNzdWU2MDQyMTAyOTc=,3991,Nondeterministic bug with bytestring decoding,23484003,closed,0,,,2,2020-04-21T18:57:28Z,2020-04-21T20:39:56Z,2020-04-21T20:39:56Z,NONE,,,,"I have an HDF5 dataset with a scalar variable called 'name' that is actual a 0-D NumPy array with dtype '|S8'. (Not my choice, this is what I get from someone else...) Occasionally, the loading fails. #### MCVE Code Sample ```python #Set up the file import h5py f = h5py.File(""error_demo.h5"",mode='w') f.create_dataset('name',shape=(),dtype=""|S8"",data=np.array([b'f(Pt,TE)'],dtype='|S8')) f.close() #Produce the error -- you may need to adjust the number of times you run the loop import xarray as xr for i in range(10): xr.load_dataset(""error_demo.h5"") ``` #### Expected Output Dimensions: () Data variables: name The resulting error message ``` Traceback (most recent call last): File """", line 1, in mcout62 = xr.load_dataset(""57062/mcout000011.h5"",group=r""part/ions/dE(r,z,D)"") File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/backends/api.py"", line 261, in load_dataset return ds.load() File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/dataset.py"", line 659, in load v.load() File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/variable.py"", line 375, in load self._data = np.asarray(self._data) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py"", line 85, in asarray return array(a, dtype, copy=False, order=order) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/indexing.py"", line 677, in __array__ self._ensure_cached() File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/indexing.py"", line 674, in _ensure_cached self.array = NumpyIndexingAdapter(np.asarray(self.array)) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py"", line 85, in asarray return array(a, dtype, copy=False, order=order) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/indexing.py"", line 653, in __array__ return np.asarray(self.array, dtype=dtype) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py"", line 85, in asarray return array(a, dtype, copy=False, order=order) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/indexing.py"", line 557, in __array__ return np.asarray(array[self.key], dtype=None) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/backends/netCDF4_.py"", line 73, in __getitem__ key, self.shape, indexing.IndexingSupport.OUTER, self._getitem File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/core/indexing.py"", line 837, in explicit_indexing_adapter result = raw_indexing_method(raw_key.tuple) File ""/Users/lmorton/opt/anaconda3/lib/python3.7/site-packages/xarray/backends/netCDF4_.py"", line 85, in _getitem array = getitem(original_array, key) File ""netCDF4/_netCDF4.pyx"", line 4408, in netCDF4._netCDF4.Variable.__getitem__ File ""netCDF4/_netCDF4.pyx"", line 5384, in netCDF4._netCDF4.Variable._get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 9: invalid start byte ``` #### Versions
Output of xr.show_versions() INSTALLED VERSIONS ------------------ commit: None python: 3.7.6 (default, Jan 8 2020, 13:42:34) [Clang 4.0.1 (tags/RELEASE_401/final)] python-bits: 64 OS: Darwin OS-release: 19.4.0 machine: x86_64 processor: i386 byteorder: little LC_ALL: en_US.UTF-8 LANG: en_US.UTF-8 LOCALE: en_US.UTF-8 libhdf5: 1.10.4 libnetcdf: 4.7.3 xarray: 0.15.0 pandas: 1.0.1 numpy: 1.18.1 scipy: 1.4.1 netCDF4: 1.5.3 pydap: None h5netcdf: None h5py: 2.10.0 Nio: None zarr: None cftime: 1.0.4.2 nc_time_axis: None PseudoNetCDF: None rasterio: None cfgrib: None iris: None bottleneck: 1.3.2 dask: 2.11.0 distributed: 2.11.0 matplotlib: 3.1.3 cartopy: None seaborn: 0.10.0 numbagg: None setuptools: 46.0.0.post20200309 pip: 20.0.2 conda: 4.8.3 pytest: 5.3.5 IPython: 7.12.0 sphinx: 2.4.0
","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/3991/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 203543958,MDU6SXNzdWUyMDM1NDM5NTg=,1233,2D coordinates to DataArray: erroneous error message,23484003,closed,0,,,3,2017-01-27T02:20:22Z,2019-02-23T08:47:00Z,2019-02-23T08:47:00Z,NONE,,,,"I've got a dataset where one of the coordinates is time, and the other is space, but the spatial coordinate is time-dependent (ie, probe is moving), so I need a different set of x-values at each time point. If I run: ``` from numpy import empty import xarray as xr data=empty((4,5)) x=empty((4,5)) t=empty((4)) xc=('x', x) tc=('t',t) xr.DataArray(data,coords=(tc,xc)) ``` I get this traceback: ``` /home/anaconda/lib/python2.7/site-packages/xarray/core/variable.pyc in _parse_dimensions(self, dims) 335 def _parse_dimensions(self, dims): 336 if isinstance(dims, basestring): 337 dims = (dims,) 338 dims = tuple(dims) 339 if len(dims)!=self.ndim: 340 raise ValueError('dimensions %s must have the same length as the ' 341 'number of data dimensions, ndim=%s' --> 342 % (dims, self.ndim)) 343 return dims 344 ValueError: dimensions ('x',) must have the same length as the number of data dimensions, ndim=2 ``` It looks like the error-check is not functioning correctly, because 'x' obviously has dimension=2, same as 'data'. It would also be helpful to state *both* the dimensions that are being compared in the error message, and make it clear which is which.","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/1233/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue 215821510,MDU6SXNzdWUyMTU4MjE1MTA=,1315,Logarithmic colorbar ticks are jumbled ,23484003,closed,0,,,1,2017-03-21T17:37:45Z,2017-03-21T17:46:00Z,2017-03-21T17:44:47Z,NONE,,,,"When I use LogNorm to get a logarithmic color scale for an xarray's self-plotting feature, the logarithmic ticks on the colorbar appear to be overplotted with a linear scale. If any of the data is out-of-range (ie, I set vmax & vmin) the problem only gets worse. Here are my specs: Python 2.7.13 |Anaconda custom (64-bit) IPython 5.2.2 -- An enhanced Interactive Python. Using matplotlib backend: TkAgg Numpy: 1.11.3 Matplotlib: 2.0.0 xarray: 0.9.1 The code is: `import numpy from matplotlib.colors import LogNorm import xarray data=numpy.random.random((10,12))*100.0+0.1 xr=xarray.DataArray(data,dims=['t','x']) xr.plot(norm=LogNorm())` This is what it looks like: ![lognormmess](https://cloud.githubusercontent.com/assets/23484003/24161646/6ca75118-0e3b-11e7-9943-6178d24656cf.png)","{""url"": ""https://api.github.com/repos/pydata/xarray/issues/1315/reactions"", ""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,completed,13221727,issue