一、读nc文件画出降水概率的分布
给了一个降水的nc文件,读取lon lat pre,创建画布,选择投影,设置colorbar,plot.savefig(),plt.show()出图!
1 import xarray as xr 2 import matplotlib.pyplot as plt 3 import cartopy.crs as ccrs 4 5 6 7 ds=xr.open_dataset("/home/kwang/PY/keshihua/plot_exp1/relativeuncertainty.nc") 8 9 lats = ds.variables['lat'][:] 10 lons = ds.variables['lon'][:] 11 precipitation=ds.variables['precipitation'][0, :, :] 12 fig = plt.figure() #空白画板 13 ax = plt.axes(projection=ccrs.Robinson()) #设置轴域,在fig中来一个轴,Robinson是伪圆柱投影, 14 plt.contourf(lons, lats, precipitation) 15 plt.colorbar(shrink = 0.8,orientation='horizontal',label='Precipitation Uncertainty (%)') 16 plt.savefig('/home/kwang/PY/keshihua/plot_exp1/PrecipitationUncertainty2.png', format='png',dpi=400) 17 plt.show()
???不理解为什么改了投影类型,图还是没有变...
投影类型看的是园里一个老哥的(d=====( ̄▽ ̄*)b):(一)Cartopy中的地图投影 - 气象学人 - 博客园 (cnblogs.com)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
二、读EXCEL文件做scatter的图
先定义了一个函数def plot_validation_metric ,然后在函数定义里面写语句,最后直接在函数外面用这个语句就ok。
(目前里面还是有些语句没搞懂,例如那个循环,等老师讲了后更新)
1 import numpy as np 2 #from pylab import rcParams 3 import matplotlib.pyplot as plt 4 from matplotlib import colors 5 import pandas as pd 6 import cartopy.crs as ccrs 7 import cartopy 8 9 #from mpl_toolkits.basemap import Basemap 10 11 def plot_validation_metric(dir_fig, data): 12 fig = plt.figure(figsize=(10, 5)) 13 plt.interactive(False) 14 ax = fig.add_subplot(1, 1, 1, projection=ccrs.Robinson()) 15 #ax.set_extent([180, -180, -60, 60]) 16 #ax.set_extent([ext_e, ext_w, ext_s, ext_n]) 17 IGBPs = ['DBF','EBF','ENF','MF','SH','SAV','GRA','WET','CRO'] 18 sybs = ["v","^","<",">","o","s","*","d","D"] 19 cpools = ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4','#313695','#393695'] 20 for IGBP,syb, cpool in zip(IGBPs, sybs,cpools): 21 ind = data[data['IGBP_veg_class'] == IGBP].index 22 data_select = data.loc[ind] 23 lon_select = data_select['lon'].values 24 lat_select = data_select['lat'].values 25 ax.scatter(lon_select, lat_select, marker=syb, linewidth=0,label=IGBP,s=150, alpha=0.7, zorder=2, 26 transform=ccrs.PlateCarree()) 27 ax.legend(fontsize=10, loc=3, bbox_to_anchor=(0.06, 0.20, 0.5, 0.5)) 28 ax.add_feature(cartopy.feature.LAKES, edgecolor='None',zorder=1) 29 30 # make the map global rather than have it zoom in to 31 # the extents of any plotted data 32 ax.set_global() 33 ax.stock_img() 34 ax.coastlines(resolution='110m') 35 #rivers_50m = cartopy.feature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '50m') 36 #ax.plot(gauge_lon,gauge_lat, 'o',markersize=10,color="red",alpha=0.7,zorder=2,transform=ccrs.PlateCarree()) 37 38 plt.tight_layout() 39 40 #ax.add_feature(rivers_50m, facecolor='None', edgecolor='b',zorder=4) 41 plt.savefig('/home/kwang/PY/keshihua/plot_exp2/test2.png' , format='png',dpi=600) 42 plt.show() 43 44 if __name__=='__main__': 45 dir_Fig = './' 46 data_dir = './' 47 data = pd.read_excel('/home/kwang/PY/keshihua/plot_exp2/fluxnet_map.xlsx') 48 #ind = data[data['IGBP_veg_class'] == 'GRA'].index 49 #data_select = data.loc[ind] 50 #lon_select = data_select['lon'].values 51 #lat_select = data_select['lat'].values 52 #data_select0 = data.loc[ind] 53 #ind2 = data_select0[data_select0['Bset'] == 5].index 54 #data_select = data.loc[ind2] 55 #KGE_select = data_select['MAX'].values 56 #lon_select = data_select['lon'].values 57 #lat_select = data_select['lat'].values 58 59 #cpool = ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'] 60 #cmap = colors.ListedColormap(cpool) 61 #norm = colors.BoundaryNorm(bnd, cmap.N) 62 plot_validation_metric(dir_Fig, data)
三、读取地表温度的nc文件,做出动图
这个在画的时候需要装两个geocat的库,一个是geocat-viz, geocat-comp。这两个都是在wsl里面装好的,在自己定义的一个环境里面安装成功的!!!(只能在linux和macos里面安装)!!!,服务器上不知道为什么也装不上,只装好了viz。。。
Geocat Comp :: Anaconda.org 这里可以直接在conda官网上查到指定包的安装指令。
先是通过循环生成35张图,每个间隔10°经度,然后最后通过os.system("convert -delay 0 ts??.png -loop 0 ts.gif") 指令,讲这35张图合并为一张GIF。
———————————————————————————————————————————————————————————
1 import numpy as np 2 import xarray as xr 3 import cartopy.crs as ccrs 4 import matplotlib.pyplot as plt 5 from geocat.viz import util as gvutil 6 import os 7 import matplotlib 8 from pylab import rcParams 9 10 ### Plot settings 11 font = {'family' : 'DejaVu Sans'} 12 #font = {'family' : 'Myriad Pro'} 13 matplotlib.rc('font', **font) 14 15 params = {'backend': 'ps', 16 'axes.labelsize': 12, 17 'grid.linewidth': 0.2, 18 'font.size': 15, 19 'legend.fontsize': 12, 20 'legend.frameon': False, 21 'xtick.labelsize': 12, 22 'xtick.direction': 'out', 23 'ytick.labelsize': 12, 24 'ytick.direction': 'out', 25 'savefig.bbox': 'tight', 26 'axes.unicode_minus': False, 27 'text.usetex': False} #提前设定好画图的参数,这样后面就不用边画边设置 28 rcParams.update(params) 29 30 31 32 # Generate figure (set its size (width, height) in inches) 33 fig = plt.figure(figsize=(10, 10)) 34 35 ############################################################################### 36 # Read in data: 37 38 # Open a netCDF data file using xarray default engine and load the data into xarrays 39 ds = xr.open_dataset("/home/kwang/PY/keshihua/plot_exp3/atmos.nc", decode_times=False) 40 for i in range (0,35): 41 t = ds.TS.isel(time=0) 42 43 ############################################################################### 44 # Fix the artifact of not-shown-data around 0 and 360-degree longitudes 45 wrap_t = gvutil.xr_add_cyclic_longitudes(t, "lon") 46 47 ############################################################################### 48 #Plot: 49 50 51 # Generate axes using Cartopy and draw coastlines with 52 ax = plt.axes( 53 projection=ccrs.Orthographic(central_longitude=-180+i*10, central_latitude=50)) 54 ax.set_extent([0, -180, 0, 90], ccrs.PlateCarree()) 55 ax.set_global() 56 ax.coastlines(linewidths=0.5) 57 temp = wrap_t.plot.contourf( 58 ax=ax, 59 transform=ccrs.PlateCarree(), 60 levels=11, 61 cmap='coolwarm', 62 add_colorbar=False) 63 64 cbar_ticks = np.arange(210, 311, 10) 65 cbar = plt.colorbar(temp, 66 orientation='horizontal', 67 shrink=0.75, 68 pad=0.05, 69 extendrect=True, 70 ticks=cbar_ticks) 71 72 cbar.ax.tick_params(labelsize=10) 73 gvutil.set_titles_and_labels(ax, 74 maintitle="Example of Orthogonal Projection", 75 lefttitle="Surface Temperature", 76 righttitle="K") 77 78 plt.savefig("/home/kwang/PY/keshihua/plot_exp3/ts"+str(i).zfill(2)+".png") 79 # Show the plot 80 #plt.show() 81 82 os.system("convert -delay 0 ts??.png -loop 0 ts.gif")
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)