如何使用Python和Basemap绘制不规则间隔的RGB图像?
我有三个矩阵,它们描述了我想要绘制的数据:
- lons - 一个二维矩阵,大小为 [n_lons,n_lats]
- lats - 一个二维矩阵,大小为 [n_lons,n_lats]
- dataRGB - 一个三维矩阵,大小为 [n_lons,n_lats,3]
我想知道用Python和Basemap绘制这些数据的最佳方法是什么。
对于伪彩色数据,使用pcolormesh方法非常简单:
data - 一个二维矩阵,大小为 [n_lons,n_lats]
m = Basemap(...)
m.pcolormesh(lons,lats,data,latlon=True)
根据我阅读的文档,似乎在这种情况下应该使用imshow命令,但这个方法需要规则网格的数据,而我需要重新网格化和插值我的数据。
有没有其他方法可以绘制这些数据呢?
1 个回答
2
我之前也遇到过这个问题,这是我找到的唯一解决办法:
(注意,这个方法在matplotlib 1.3.0版本下有效,但在1.1.0版本下无效)
from mpl_toolkits.basemap import Basemap
import numpy.ma as ma
import numpy as np
m = Basemap() #Define your map projection here
假设var是你关注的变量(大小为NxMx3),lats是(N)x(M),lons也是(N)x(M):
我们需要把像素中心的纬度和经度转换为像素角落的纬度和经度(大小为(N+1)x(M+1))
cornerLats=getCorners(lat);cornerLons=getCorners(lon)
获取坐标的角落位置
xCorners,yCorners=m(cornerLats,cornerLons,inverse=True)
屏蔽掉无效的数据
var=ma.masked_where(np.isnan(var),var)
我们需要一个扁平化的元组(大小为N*M,3),以便传递给pcolormesh
colorTuple=tuple(np.array([var[:,:,0].flatten(),var[:,:,1].flatten(),var[:,:,2].flatten()]).transpose().tolist())
设置更大的线宽会导致边缘失真,而设置更小的线宽会让图像出现奇怪的问题。
m.pcolormesh(xCorners,yCorners,var[:,:,0],color=colorTuple,clip_on=True,linewidth=0.05)
def getCorners(centers):
one = centers[:-1,:]
two = centers[1:,:]
d1 = (two - one) / 2.
one = one - d1
two = two + d1
stepOne = np.zeros((centers.shape[0] + 1,centers.shape[1]))
stepOne[:-2,:] = one
stepOne[-2:,:] = two[-2:,:]
one = stepOne[:,:-1]
two = stepOne[:,1:]
d2 = (two - one) / 2.
one = one - d2
two = two + d2
stepTwo = np.zeros((centers.shape[0] + 1,centers.shape[1] + 1))
stepTwo[:,:-2] = one
stepTwo[:,-2:] = two[:,-2:]
return stepTwo