Skip to main content
 首页 » 编程设计

python之覆盖代表等高线图上重要点的补丁

2024年10月24日7shihaiming

我正在尝试在等高线图上添加阴影线(如点、散列、..)。这样的影线可以代表唯一具有统计显着性的轮廓,或具有特定标准的轮廓。喜欢下图自然文章(第二和第三情节)http://www.nature.com/articles/srep16853/figures/3 .

以下代码显示来自 NOAA 数据的降水图 available下载地址:

import numpy as np 
import sys  
import netCDF4 as nc 
import matplotlib.pyplot as plt 
import matplotlib.mlab as m  
import mpl_toolkits.basemap as bm 
import os 
sys.path.insert(0, '../');import py4met as sm;reload(sm) 
 
#- Reading data for a timeslice, latitude, and longitude: 
diri_output="./" 
diri="./" 
tmp_file = nc.Dataset(diri+"precip.mon.mean.nc","r") 
print(tmp_file.variables) 
p_pre   = tmp_file.variables['precip'] 
lat     = tmp_file.variables['lat'][:] 
lon     = tmp_file.variables['lon'][:] 
time    = tmp_file.variables['time'] 
tmp_file.close 
 
 
lat1=np.min(lat) 
lat2=np.max(lat) 
lon1=np.min(lon) 
lon2=np.max(lon) 
 
[lonall, latall] = np.meshgrid(lon[:], lat[:]) 
plt.figure(num=None, figsize=(8+4, 6+4), dpi=80, facecolor='w', edgecolor='k')     
mapproj = bm.Basemap(projection='cyl',llcrnrlat=lat1, llcrnrlon=lon1,urcrnrlat=lat2, urcrnrlon=lon2,resolution='l') 
mapproj.drawcoastlines() 
mapproj.drawmapboundary(fill_color='white') 
mapproj.drawcountries() 
x, y = mapproj(lonall, latall) 
plt.contourf(x,y,p_pre[240,:,:],cmap=plt.cm.GnBu) 
plt.colorbar(orientation='horizontal',pad=0.05,shrink=0.6) 
plt.title("title") 
xx,yy=np.where(p_pre[240,:,:] >= 20) 
sig=np.copy(p_pre[0,:,:]) 
sig[:,:]=1 
sig[xx,yy]=0 
#plt.contourf(x,y,sig,hatches=['.']) 
plt.show()   

我想对20mm以上的所有轮廓进行孵化,所以用了上面的命令

plt.contourf(x,y,sig,hatches=['.'])

但它没有用(它在 map 上到处都是点,而不仅仅是具有特定标准的轮廓),因此我评论了它。 任何想法。

请您参考如下方法:

查看此 matplotlib example page演示如何使用 contourf 使用影线。与您的问题特别相关的是 (1) contourf 采用关键字 level 来确定哪些值被着色和/或影线的界限,并且( 2) 空字符串 "" 可用于缺少舱口。

因此,您注释掉的不是 plt.contourf 行

levels = [p_pre[240,:,:].min(), 20, p_pre[240,:,:].max()] 
plt.contourf(x, y, p_pre[240,:,:], levels=levels, hatches=["", "."], alpha=0) 

我无法根据您链接到的数据重新创建您的绘图,因此我生成了一些随机数据,使用我上面描述的相同原理制作下面的图像。