numpy 如何pcolormesh RGBA阵列与2D x和y?

11dmarpk  于 2023-04-12  发布在  其他
关注(0)|答案(2)|浏览(129)

我有一个RGBA数组(img),其中有2D x和y,如下所示:

import numpy as np
import matplotlib.pyplot as plt

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, 4))

根据这个question,我们可以传递任何数组来绘图,并使用img设置颜色:

fig, axs = plt.subplots()
axs.pcolormesh(x, y, img[:, :,0], color=img.reshape((img.shape[0]*img.shape[1]), 4)/255)

但是,它只是改变了edgecolors。

我想把它显示为axs.imshow(img)

23c0lvtd

23c0lvtd1#

更新:这里是给定the trick you found的完整示例代码,以阻止颜色Map颜色的分配。

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(100)

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

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

fig, ax = plt.subplots()
mesh = ax.pcolormesh(x, y, img[:, :,0], facecolors=img.reshape(-1, 4)/255)
# This is necessary to let the `color` argument determine the color
mesh.set_array(None)
plt.show()

PS:还要注意,img.reshape(-1, 4)img.reshape(img.shape[0]*img.shape[1], 4)的一个快捷(更易于维护)版本。
还要注意的是,xy是指单元格之间的边界,并且需要比每个维度中的单元格数量多一个值。因此,我将np.arange(10, 20)增加到np.arange(10, 21),但是如果你想让10..19作为中心,你需要减去0.5作为边界的位置(例如np.arange(10, 21) - 0.5)。
正如Jody Klymak评论的那样,建议不要使用color,它指的是facecoloredgecolor。由于边缘与相邻的边缘重叠,当透明度发挥作用时,会出现一些奇怪的效果。

nkcskrwz

nkcskrwz2#

从Matplotlib v3.7开始,RGB(A)数组可以直接传递。https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.7.0.html#pcolormesh-accepts-rgb-a-colors

import numpy as np
import matplotlib.pyplot as plt

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, 4)) / 255

fig, axs = plt.subplots()
axs.pcolormesh(x, y, img)
plt.show()

编辑:注意我将img数组转换为float,就像原始数组给我的那样

ValueError: Image RGB array must be uint8 or floating point; found int64

相关问题