简体   繁体   English

如何使用 2D x 和 y 对 RGBA 数组进行 pcolormesh?

[英]How to pcolormesh RGBA array with 2D x and y?

I have a RGBA array ( img ) with 2D x and y like this:我有一个带有 2D x 和 y 的 RGBA 数组( img ),如下所示:

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

According to this question , we can pass any array to plot and set the color using img :根据这个问题,我们可以将任何数组传递给 plot 并使用img设置颜色:

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

However, it just changed the edgecolors.然而,它只是改变了边缘颜色。

边缘颜色

I want to show it like axs.imshow(img)我想像axs.imshow(img)一样显示它

显示

Maybe matplotlib has changed a bit how it works?也许 matplotlib 已经改变了一点它是如何工作的? (Or maybe the old question only works with Basemap ?) Now the colormapping is only assigned when the plot is drawn, so overwriting colors assigned via color= . (或者也许老问题只适用于Basemap ?)现在颜色映射仅在绘制 plot 时分配,因此覆盖通过color=分配的 colors 。

What seems to work is a dummy draw and only then assign new colors:似乎有效的是一个虚拟抽奖,然后才分配新的 colors:

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])
fig.canvas.draw() # dummy redraw
mesh.set_color(img.reshape(-1, 4)/255)
plt.show()

改变颜色的 pcolormesh

PS: Also note that img.reshape(-1, 4) is a shortcut (and more maintainable) version of img.reshape(img.shape[0]*img.shape[1], 4) . PS:还要注意img.reshape(-1, 4)img.reshape(img.shape[0]*img.shape[1], 4)的快捷方式(并且更易于维护)版本。

Also note that the x and y refer to the borders between the cells, and there need to be one value more than the number of cells in each dimension.另请注意, xy指的是单元格之间的边界,并且需要比每个维度中的单元格数多一个值。 Therefore, I incremented np.arange(10, 20) to np.arange(10, 21) , but if you want 10..19 as centers, you need to subtract 0.5 for the position of the border (as eg np.arange(10, 21) - 0.5 )因此,我np.arange(10, 20)增加到np.arange(10, 21) ,但是如果您想要10..19作为中心,则需要为边界的 position 减去0.5 (例如np.arange(10, 21) - 0.5 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM