【发布时间】:2017-05-16 02:06:45
【问题描述】:
我正在尝试绘制全球气溶胶光学深度 (AOD),该值通常在 0.2 左右,但在某些地区可以达到 1.2 或更高。理想情况下,我想绘制这些高值,而不会丢失较小值的细节。对数刻度颜色条也不是很合适,所以我尝试使用docs 中描述的两个线性范围:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import cartopy.crs as ccrs
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
res = np.ma.masked_array(np.interp(value, x, y))
return res
但是,当我尝试使用 Cartopy 绘制 pcolormesh 绘图时,这会中断。根据画廊示例之一创建虚拟数据:
def sample_data(shape=(73, 145)):
"""Returns ``lons``, ``lats`` and ``data`` of some fake data."""
nlats, nlons = shape
lats = np.linspace(-np.pi / 2, np.pi / 2, nlats)
lons = np.linspace(0, 2 * np.pi, nlons)
lons, lats = np.meshgrid(lons, lats)
wave = 0.75 * (np.sin(2 * lats) ** 8) * np.cos(4 * lons)
mean = 0.5 * np.cos(2 * lats) * ((np.sin(2 * lats)) ** 2 + 2)
lats = np.rad2deg(lats)
lons = np.rad2deg(lons)
data = wave + mean
return lons, lats, data
ax = plt.axes(projection=ccrs.Mollweide())
lons, lats, data = sample_data()
ax.contourf(lons, lats, data,
transform=ccrs.PlateCarree(),
cmap='spectral', norm=MidpointNormalize(midpoint=0.8))
ax.coastlines()
ax.set_global()
plt.show()
但是,当使用 pcolormesh 等效项似乎不起作用时,它具有一组 0 到 180 度经度之间的模糊值(图的右半部分),而不是等值线图中看到的波浪图案:
ax.pcolormesh(lons, lats, data,
transform=ccrs.PlateCarree(),
cmap='spectral', norm=MidpointNormalize(midpoint=0.8))
我怎样才能使 pcolormesh 工作?当我对 Cartopy 投影/转换做错了什么时,我通常会看到这一点,所以大概这与 Cartopy 环绕日期线的方式或简单的 matplotlib 示例忽略的边缘情况之一有关,但我想不通出来吧。
请注意,这只发生在使用自定义 Normalization 实例时;没有它,pcolormesh 也会按预期工作。
【问题讨论】:
-
@ImportanceOfBeingErnest pcolormesh 示例(第二个图)具有一组介于 0 和 180 度经度之间的模糊值,而不是等值线图中看到的波浪形图案。当我对 Cartopy 投影/转换做错了事时,我通常会看到这种情况......
-
好的,谢谢。我已经编辑了这个问题,试图让它更清楚。 0-180度经度是图的右半部分,它应该与左半部分对称(如等高线图)。
-
是的,只有在使用 MidpointNormalize 来规范色标时。是的,应该是……!
标签: python matplotlib cartopy