python - 将 netcdf 文件的所有时间步长绘制成 map

标签 python plot netcdf

我想知道是否可以将这个单个 netcdf 文件中的所有步骤绘制到单独的图中。

步骤113表示当前访问的数据是2019年10月22日的数据。第 0 步是 2019 年 7 月 1 日。总共有 135 个时间步。这意味着我每天需要制作 135 张 map 。

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];

这是我到目前为止的代码。

import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm


Data=xr.open_dataset('PMs ECMWF2.nc')

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];


nlon, nlat = np.meshgrid(X,Y)


fig, ax = plt.subplots(figsize=(12, 12), dpi=300)

# Add Plotting the plot
ax=plt.subplot(111,projection=ccrs.PlateCarree())

# Add Plot features
ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
ax.coastlines('50m', linewidth=0.8)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS, edgecolor="yellow")
ax.add_feature(cf.COASTLINE, edgecolor="yellow")
ax.add_feature(cf.RIVERS)
ax.gridlines()

#changing the location of the map
ax.set_extent([90, 141, 24, -10])

# Add gridlines, and set their font size
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='black', alpha=0.05, linestyle='-')
gl.top_labels = False
gl.left_labels = True
gl.right_labels = False
gl.xlines = True
gl.ylines = True

#colorbar
cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic

# plotting the variables
pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours


#plotting the quiver
ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')


#plot title 
#plt.title('Carbon Monoxide on October 22, 2019')

plt.show()

到目前为止,此代码仅生成一张图像。我必须一遍又一遍地这样做。 enter image description here

最佳答案

创建一个循环时间变量和循环内变量映射的示例如下:

#!/usr/bin/env ipython
# ---------------------------
import numpy as np
from netCDF4 import Dataset,num2date
# ---------------------------
# let us generate data, preferably to the netcdf:
nx=50;ny=50;ntime=10;
A=np.random.random((ntime,ny,nx));
lon = np.linspace(0,360,nx);
lat = np.linspace(-90,90,ny);
time = np.linspace(0,366,ntime);timeunit = 'days since 2020-01-01 00:00:00'
fout = 'test.nc'
with Dataset(fout,'w') as f:
    f.createDimension('longitude',nx);
    f.createDimension('latitude',ny);
    f.createDimension('time',);
    xv = f.createVariable('longitude','float32',('longitude'));xv[:]=lon
    yv = f.createVariable('latitude','float32',('latitude'));yv[:]=lat;
    tv = f.createVariable('time','float32',('time'));tv[:]=time;tv.setncattr('units',timeunit);
    u10 = f.createVariable('u10','float32',('time','latitude','longitude'));u10[:]=A;
    v10 = f.createVariable('v10','float32',('time','latitude','longitude'));v10[:]=-A;
    pm2 = f.createVariable('pm2p5','float32',('time','latitude','longitude'));pm2[:]=A;
    
# -----------------------------------------------
# let us now make some maps:
import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm


Data=xr.open_dataset(fout)

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;

time = Data.time;

for itime in range(len(time)):
    U=Data.u10[itime]; V=Data.v10[itime];
    pm2p5=Data.pm2p5[itime];

    nlon, nlat = np.meshgrid(X,Y)


    fig, ax = plt.subplots(figsize=(12, 12), dpi=300)

    # Add Plotting the plot
    ax=plt.subplot(111,projection=ccrs.PlateCarree())

    # Add Plot features
    ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
    ax.coastlines('50m', linewidth=0.8)
    ax.add_feature(cf.LAKES)
    ax.add_feature(cf.OCEAN)
    ax.add_feature(cf.BORDERS, edgecolor="yellow")
    ax.add_feature(cf.COASTLINE, edgecolor="yellow")
    ax.add_feature(cf.RIVERS)
    ax.gridlines()

    #changing the location of the map
    ax.set_extent([90, 141, 24, -10])

    # Add gridlines, and set their font size
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='black', alpha=0.05, linestyle='-')
    gl.top_labels = False
    gl.left_labels = True
    gl.right_labels = False
    gl.xlines = True
    gl.ylines = True

    #colorbar
    cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic

    # plotting the variables
    pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
    plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours


    #plotting the quiver
    ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')


   #plot title 
   #plt.title('Carbon Monoxide on October 22, 2019')
    plt.savefig('fig_'+str(itime).rjust(3,'0')+'.png',bbox_inches='tight');
    plt.show();
    # ----------------------------

我首先生成一个具有随机值的 netCDF,然后绘制每个时刻的变量。

关于python - 将 netcdf 文件的所有时间步长绘制成 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67583375/

相关文章:

python - 在Python中从另一个类创建一个类对象

r - 更改稀疏相关矩阵的图形表示

r - 如何在 R 中将 mtext() 旋转 180 度

python - 在 Python 中从数据点中查找移动平均值

xml - 使用 ncml 聚合 netcdf 文件?

python - 在 scikit-learn 管道中使用 gensim word2vec

python - 条件生成器表达式的意外行为

python - Keras - 获得训练层的重量

r - 使用 maptools - R 绘制国家边界

r - 使用 R 转换为 NetCDF 时保留栅格变量名称