使用 x-aaray 绘制选定的坐标范围 编辑:

问题描述

我正在尝试从 3-D 数据网格进行绘图。例如:

data10.isel(z=76,x=256).plot(ax=ax1)

给出以下输出

Plot1

我只想绘制该图的顶部,以便更容易比较多条曲线。我知道我们可以通过使用:

ax1.margins(-0.45,0.09)

但每次我不得不猜测/尝试括号中的数字以放大到正确的位置时。有没有办法可以设置要在绘图上显示的数据的坐标范围?

谢谢!

编辑:如何在绘制多条曲线时添加图例?

Edit2:感谢您的反馈!这是我用来绘制不同数组的代码

f,((ax1)) = plt.subplots(1,1,figsize=(5,5))
data5.isel(x=127,z=125).plot(xlim=(-25,25))
data10.isel(x=127,25))
data15.isel(x=127,25))
data20.isel(x=127,25))

给出以下输出

enter image description here

认情况下不显示图例。

编辑 3: 最后一个问题:我试图将数据数组中的选定值复制到一个列表中,然后以特定格式写入文本文件。:

data = []
data = data5.isel(x=127,z=125)

但这也会复制坐标,例如:data[200] 给出:

<xarray.DataArray ()>
array(0.)
Coordinates:
    z        float64 25.5
    y        float64 26.7
    x        float64 0.2

这样做的正确方法是什么? 弄清楚这一点:data[200].data 给出了存储在数组中的值。

解决方法

要限制您正在绘制的轴之一的边距,只需将 xlim/ylim 传递给 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()

给你

enter image description here

并将 x 上的 Latitude 轴限制为 30-60

xx.plot(xlim=(30,60))

enter image description here

如果您绘制多条线,默认情况下会添加图例:

xx = ds.sel(lon=[200,207,220],method="nearest").air

# note the slight change in syntax for multiple lines
xx.plot.line(x="lat",xlim=(30,50))

enter image description here

编辑:

要绘制来自不同数据集的多条线,您需要使用 matplotlib

xx = ds.sel(lon=200,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()

enter image description here

要访问数据集的值,您可以使用 valuesDataArray 属性(注意 air 是我数据集中的变量,将返回基础 {{1} }):

DataArray