Python 循环画图,并用不同名称命名并保存图片

        当我们画海洋和大气的一些随时间变化的多维图片时,可能每隔一个小时就要画一张,这时候就要用到for循环了

        

import numpy as np
import xarray as xr
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt  # 改变图片显示模式
import cartopy.crs as ccrs
import cartopy.mpl.ticker as cticker
from matplotlib.colors import LinearSegmentedColormap
f=xr.open_dataset('wrfout_d01_2023-12-26_00:00:00.nc')
sst=f['SST']
t=f['T2']
#result=np.where(sst==0)

lon = f['XLONG'][0,0,:]
lat = f['XLAT'][0,:,0]
lon=lon.values
lat=lat.values
save_path='wrfoutpicture'保存的文件夹,提前在程序文件坐在的文件夹里创建一个这个名字的文件夹
for i in range(0,143,6):#每隔六小时画一张
    day=i//24+26#天
    h=i%24#小时
    timestr=str(day)+'.'+str(h)#按不同时间给图片title
    name=timestr+'T differernce.png'#按时间命名
    sst1=sst[i,:,:]
    t1=t[i,:,:]#提取数据
    sst1=np.where(sst1==0,np.nan,sst1)#陆地的SST是0,得把它变成nan值
    tspan=sst1-t1#海气温差
    u=f['U10'][i,:,:]                              
    v=f['V10'][i,:,:]
    u=u.values
    v=v.values
    fig = plt.figure(figsize=(16, 12))
    ax1 = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=180))
    ax1.set_extent([113,127,26,38])
    ax1.coastlines()  # 画岸线
    # 设置横纵坐标刻度、显示方式和label
    ax1.gridlines(crs=ccrs.PlateCarree())
    ax1.set_xticks(np.arange(113,127,1), crs=ccrs.PlateCarree())
    ax1.set_yticks(np.arange(26, 38,1), crs=ccrs.PlateCarree())
    ax1.set_xlabel('longitude', fontsize=14)
    ax1.set_ylabel('latitude', fontsize=14)
    ax1.xaxis.set_major_formatter(cticker.LongitudeFormatter())
    ax1.yaxis.set_major_formatter(cticker.LatitudeFormatter())
    myCmap = LinearSegmentedColormap.from_list("", [(0.000, "#0000FF"),(1.000, "#FF0000")])#colormap
    le=np.arange(-8,8,1)
    c1 = ax1.contourf(lon, lat, tspan,levels=le,cmap=plt.get_cmap('seismic'),transform=ccrs.PlateCarree())  # 等值线填充图
    c2=ax1.quiver(lon,lat,u,v,transform=ccrs.PlateCarree())
    ax1.set_title(timestr+'T difference', fontsize=18)  # 标题
    colorbar = fig.colorbar(c1, ax=ax1, label='td')  # 设置colorbar
    plt.savefig(os.path.join(save_path,name), dpi=400)  # 保留png图片到特定文件夹

利用循环将数据变为时间,然后转为字符就行,这里提前建了文件夹save_path),方便查找,当然你也可以在程序里直接用mkdir创建文件夹。得到图片列表

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿翔_ocean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值