如何使用 matplotlib.pyplot.contourf 绘制密度数组

问题描述 投票:0回答:1

我有一个名为 dens 的 xarray 数据集,我想绘制它。

这是数据集:

<xarray.Dataset>
Dimensions:  (time: 641, lat: 30, lon: 30)
Coordinates:
  * time     (time) datetime64[ns] 2013-07-01T12:00:00 ... 2013-08-02T12:00:00
  * lon      (lon) float64 32.73 32.83 32.94 33.05 ... 35.53 35.64 35.75 35.85
  * lat      (lat) float64 31.08 31.27 31.47 31.66 ... 36.06 36.25 36.44 36.63
Data variables:
    density  (time, lat, lon) float64 2e+03 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0

我正在使用命令


plt.contourf(dens.density.values[-1,:,:]);

绘制它并且它正在工作,但由于我希望海岸线也绘制在绘图上,所以我也尝试使用

m = Basemap(llcrnrlon=data['lon'].min(), llcrnrlat=data['lat'].min(),
                urcrnrlon=data['lon'].max(), urcrnrlat=data['lat'].max(), resolution='i', suppress_ticks=1)
m.drawcoastlines();
m.fillcontinents(color='gray',lake_color='gray');

但是当我运行所有命令,然后运行

plt.show()
时,等值线图消失了,它向我显示的只是海岸线。

如何修复此问题以获得同一图中的等高线图+海岸线图?

抱歉,如果这是一个愚蠢的问题,但我对 python 还很陌生

感谢您的帮助,

约塔姆

编辑:我现在才意识到我正在尝试组合两个不同的“工具包”,并且有可能仅使用底图工具包来完成所有这些工作,但只是尝试编写

m.contourf(dens.density.values[-1,:,:]);

给了我这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[21], line 1
----> 1 m.contourf(dens.density.values[-1,:,:])

TypeError: Basemap.contourf() missing 2 required positional arguments: 'y' and 'data'

另一个编辑:我不断发现更多的东西,在阅读了 Basemap 的文档后,我意识到命令的语法应该是这样的

m.contourf(dens.lon.values,dens.lat.values,dens.density.values[-1,:,:]);

但现在我收到此错误:

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

我猜这是因为我的密度数组是二维的,但是如何从中提取密度值?我在时间维度中使用 [-1] 因为我实际上只需要最后一个时间步

再次提前致谢, 约塔姆

python python-3.x matplotlib python-xarray matplotlib-basemap
1个回答
0
投票

使用底图和 xarray 进行绘图已经在here进行了讨论。

m = Basemap(llcrnrlon=data['lon'].min(), llcrnrlat=data['lat'].min(),
            urcrnrlon=data['lon'].max(), urcrnrlat=data['lat'].max(), 
  resolution='i', suppress_ticks=1)
m.drawcoastlines();
m.fillcontinents(color='gray',lake_color='gray')
dens.density[-1,:,:].plot.contourf()
plt.show()

上面的代码应该可以工作。 我使用 cartopy 来处理海岸线和边界等功能。以下是供您尝试使用数据集的工作代码片段。

import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cf

ds = xr.open_dataset('filename.nc')
fig = plt.figure(figsize=(8,8))
crs=ccrs.PlateCarree()
ax = fig.add_subplot(1,1,1, projection=crs)
gl = ax.gridlines(crs=crs, draw_labels=True,
                linewidth=0.01, color='gray', alpha=0.5, linestyle='-.')

ax.add_feature(cf.COASTLINE.with_scale("50m"), lw=0.5)
ax.add_feature(cf.BORDERS.with_scale("50m"), lw=0.3)

ds.density[-1,:,:].plot.contourf()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.