You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cartopy投影轴上使用pcolormesh绘制RGB数组?

在Cartopy投影轴上绘制RGB数组的问题解决

问题背景

此前在普通Matplotlib轴上绘制RGB数组时,采用的方法是绘制单通道数组,再通过facecolors参数设置RGB组合颜色,最后调用set_array(None)清除与颜色映射的关联。尝试将该方法迁移到带Cartopy投影的轴上时,运行代码触发了错误。

原代码

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

np.random.seed(100)

x = np.arange(10, 20)
y = np.arange(0, 10)
x, y = np.meshgrid(x, y)

img = np.random.randint(low=0, high=255, size=(10, 10, 3))

ax = plt.axes(projection=ccrs.PlateCarree())

mesh = ax.pcolormesh(x, y, img[:, :,0], facecolors=img.reshape(-1, 3)/255)
mesh.set_array(None)
plt.show()

错误信息

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[59], line 17
     14 ax = plt.axes(projection=ccrs.PlateCarree())
     16 mesh = ax.pcolormesh(x, y, img[:, :,0], facecolors=img.reshape(-1, 3)/255)
---> 17 mesh.set_array(None)
     18 plt.show()

File ~/miniconda3/envs/enpt/lib/python3.10/site-packages/cartopy/mpl/geocollection.py:29, in GeoQuadMesh.set_array(self, A)
     27 def set_array(self, A):
     28     # raise right away if A is 2-dimensional.
---> 29     if A.ndim > 1:
     30         raise ValueError('Collections can only map rank 1 arrays. '
     31                          'You likely want to call with a flattened array '
     32                          'using collection.set_array(A.ravel()) instead.')
     34     # Only use the mask attribute if it is there.

AttributeError: 'NoneType' object has no attribute 'ndim'

问题根源

Cartopy自定义的GeoQuadMesh类重写了set_array方法,它不像普通Matplotlib的QuadMesh那样支持传入None作为参数,而是直接尝试访问输入参数的ndim属性,当传入None时自然触发属性不存在的错误。

解决方法

不需要调用set_array(None),改为在调用pcolormesh时传入一个空的占位数组作为颜色值参数,同时指定facecolors来设置自定义RGB颜色,这样就能跳过颜色映射的绑定,直接使用我们定义的颜色。

修正后的代码

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

np.random.seed(100)

x = np.arange(10, 20)
y = np.arange(0, 10)
x, y = np.meshgrid(x, y)

img = np.random.randint(low=0, high=255, size=(10, 10, 3))

ax = plt.axes(projection=ccrs.PlateCarree())

# 传入与单通道同形状的空数组作为占位,直接用facecolors指定RGB颜色
mesh = ax.pcolormesh(x, y, np.zeros_like(img[:, :, 0]), facecolors=img.reshape(-1, 3)/255)

plt.show()

内容的提问来源于stack exchange,提问作者zxdawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:22:53