python 用nc数据画世界地图动态变化

使用SM(Soil Moisture土壤湿度)不同年份日均值nc数据,基于basemap画动态世界地图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.animation import FuncAnimation
import netCDF4 as nc

path = 'sm_meanyear.nc'
ver = 'sm' #显示属性
vmin = 0;vmax = 0.35 #映射范围

#数据读取
data1 = nc.Dataset(path)

# 创建地图
world = Basemap(projection='mill', lat_0=0, lon_0=0, resolution='l', area_thresh=1000.0,
            llcrnrlon=-180, llcrnrlat=-60, urcrnrlon=180, urcrnrlat=90)
# 创建一个空图形
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

# 数据生成函数
def generate_data():
    t = 0
    while t<len(data1['time']):
        # 生成随时间变化的地图数据
        lon,lat=np.meshgrid(np.asarray(data1['lon']),np.asarray(data1['lat']))
        lon,lat = world(lon,lat)
        data = np.asarray(data1['%s'%(ver)][t]) 
        yield lon, lat, data,t
        t += 1

# 初始化绘图对象
im = None
title = ax.set_title('')

# 更新函数,用于更新地图内容
def update(data):
    global im
    lon, lat, data,t = data
    
    if im is not None:
        im.remove()

    im = world.pcolormesh(lon, lat, data, cmap='jet_r', shading='auto', ax=ax,vmin=vmin,vmax=vmax) #
    title.set_text(f'Time: {t+2000:d}') #设置标题
    
    return im,

# 创建动画对象
ani = FuncAnimation(fig, update, frames=generate_data, blit=True)

# 显示地图
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])
plt.colorbar(im,orientation="horizontal",pad=0.05)
# 显示动画
#plt.show()
ani.save('sm.gif')
data1.close()

你可能感兴趣的:(python可视化,python,开发语言)