Reputation: 195
I am trying to plot from a 3-D data grid. For example:
data10.isel(z=76,x=256).plot(ax=ax1)
I would like to plot just the top part of this plot so that it is easier to compare multiple curves. I know we can do it by using:
ax1.margins(-0.45,0.09)
but each time I am having to guess/trial the numbers in the bracket to zoom into the right position. Is there a way I can set the range of co-ordinates for the data that I want to be displayed on the plot?
Thanks!
Edit: How to add legends when plotting multiple curves?
Edit2: Thank you for your feedback! Here is the code I am using to plot from different arrays:
f, ((ax1)) = plt.subplots(1, 1, figsize=(5,5))
data5.isel(x=127,z=125).plot(xlim=(-25,25))
data10.isel(x=127,z=125).plot(xlim=(-25,25))
data15.isel(x=127,z=125).plot(xlim=(-25,25))
data20.isel(x=127,z=125).plot(xlim=(-25,25))
Legends do not appear by default.
Edit 3: Final Q: I am trying to copy selected values from the data array into a list to be written into a text file in a particular format.:
data = []
data = data5.isel(x=127,z=125)
But this copies the coordinates as well, for example: data[200]
gives:
<xarray.DataArray ()>
array(0.)
Coordinates:
z float64 25.5
y float64 26.7
x float64 0.2
What would be the right way to do this?
Figured this out: data[200].data
gives the value stored in the array.
Upvotes: 0
Views: 801
Reputation: 7023
To limit the margins of one of the axis you're plotting, just pass xlim
/ylim
to plot
:
import xarray as xr
ds = xr.tutorial.open_dataset("air_temperature")
xx = ds.sel(lon=200, time=ds.time.values[0], method="nearest").air
xx.plot()
gives you
and to limit the Latitude
axis on x to 30
-60
:
xx.plot(xlim=(30,60))
A legend is added by default if you plot multiple lines:
xx = ds.sel(lon=[200,207,220], time=ds.time.values[0], method="nearest").air
# note the slight change in syntax for multiple lines
xx.plot.line(x="lat", xlim=(30,50))
To plot multiple lines from different datasets, you need to use matplotlib
:
xx = ds.sel(lon=200, time=ds.time.values[0], method="nearest").air
import matplotlib.pyplot as plt
xlim = (30,60)
plt.figure()
xx.air.plot(xlim=xlim, label="Air")
(xx.air*1.5).plot(xlim=xlim, label="Air*1.5")
(xx.air*2).plot(xlim=xlim, label="Air*2")
# adds legend
plt.legend()
And to access values of your dataset, you can use the values
property of your DataArray
(note air
is the variable in my dataset and will return the underlying DataArray
):
print(xx.air.values[10:20])
#array([277.29 , 278.4 , 280. , 282.79 , 284.6 , 286.5 ,
# 287.9 , 290.19998, 293.1 , 293.79 ], dtype=float32)
Upvotes: 1