Basemap包安装
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
#数据读取
data = nc.Dataset('sm_monthly_05degree.nc')
data
#经纬度范围与空间经度查看
data['lon'][:10],data['lat'][:10]
#画图代码
def World_map(tem,levels,label,cmap,lon,lat):
#定义地图显示范围
world = Basemap(projection='mill', lat_0=0, lon_0=0, resolution='l', area_thresh=1000.0,
llcrnrlon=np.min(lon), urcrnrlon=np.max(lon), llcrnrlat=-60, urcrnrlat=90)
fig=plt.figure(figsize=(10, 8))
# 绘制海岸线、国家边界线和州边界线
world.drawcoastlines(linewidth=0.7)
# 绘制经纬度网格线
world.drawparallels(np.arange(-90.,91.,45),color='k',linewidth=0.2,labels=[1,0,0,0])
world.drawmeridians(np.arange(-180.,180.,60.),color='k',linewidth=0.2,labels=[0,0,0,1])
lon1,lat1=np.meshgrid(lon,lat)
x, y = world(lon1,lat1)
norm = mpl.colors.BoundaryNorm(boundaries=levels,ncolors=256)
#填色
world.pcolormesh(x,y,tem,cmap=cmap,norm=norm,shading='nearest')
# 添加标题
plt.xlabel(label,labelpad=20,fontsize=12)
# 显示图像
#plt.show()
plt.colorbar(orientation="horizontal",pad=0.1)
#plt.savefig('world_1.png',dpi=300)
lon = np.arange(0,360,0.5) #经度范围
lat = np.arange(-90,90,0.5) #纬度范围
levels = np.linspace(0,0.5,20) #colorbar映射范围
cmap = 'YlGnBu' #colobar映射颜色
tem = np.nanmean(data['sm'],axis=0)
World_map(tem,levels,'example',cmap,lon,lat)
#整体沿y轴平移180°,由于空间精度为0.5°,因此平移360格点
tem_roll = np.roll(tem,360,axis=1)
lon = np.arange(-180,180,0.5) #经度范围
lat = np.arange(-90,90,0.5) #纬度范围
levels = np.linspace(0,0.5,20) #colorbar映射范围
cmap = 'YlGnBu' #colobar映射颜色
World_map(tem_roll,levels,'example',cmap,lon,lat)
若纬度是从大到小排序,先可使用np.flipud(用于沿着垂直方向翻转(翻转上下顺序)数组或矩阵。它会返回一个新的翻转后的数组,而不会修改原始数组。)
plt.subplot(1, 2, 1)
plt.imshow(tem)
plt.title('Lat :-90 to 90')
tem_fliupd = np.flipud(tem)
plt.subplot(1, 2, 2)
plt.imshow(tem_fliupd)
plt.title('lat :90 to -90')