首页 > 解决方案 > 在图片上调整 python pcolor 图表

问题描述

我想在图片上放一个 pcolor 图表。您知道一种自动将颜色图匹配/调整到图片的方法吗?

示例代码:

import matplotlib.pyplot as plt
import numpy as np

# my image
im = plt.imread('salad.png')

# example pcolor chart
values = np.random.rand(6, 10)
p = plt.pcolor(values)

图片:

在此处输入图像描述

P色图:

在此处输入图像描述

我试过这个:

# Create Figure and Axes objects
fig,ax = plt.subplots(1)

# display the image on the Axes
implot = ax.imshow(image)

# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(values, alpha = 0.5, cmap='viridis')  

# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)

结果我在下面有这个,这不是我想要的。颜色图不适合整个图像范围:

在此处输入图像描述

有没有办法自动将 pcolor 图表调整为图像大小?或图像到 pcolor 图表大小?

我的意思是这样的示例结果:

在此处输入图像描述

提前感谢您的任何想法。

标签: pythonimagematplotlib

解决方案


您需要修复图像或 pcolor 叠加层的范围(即它们将被绘制的坐标范围)。

如您所见,您的图像在 x 和 y 方向的限制为 0 到 ~190,但 pcolor 在 x 和 y 方向的限制为 10 和 6。

一种选择是定义新的 x 和 y 坐标以传递给pcolor函数。

例如:

import matplotlib.pyplot as plt
import numpy as np

# my image
im = plt.imread('stinkbug.png')

# example pcolor chart
values = np.random.rand(6, 10)
#p = plt.pcolor(values)

# Create Figure and Axes objects
fig,ax = plt.subplots(1)

# display the image on the Axes
implot = ax.imshow(im)

# Define the x and y coordinates for the pcolor plot
x = np.linspace(0, im.shape[1], values.shape[1]+1)   # add 1 because we need the define the nodal coordinates
y = np.linspace(0, im.shape[0], values.shape[0]+1)

# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(x, y, values, alpha = 0.5, cmap='viridis')  

# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)

plt.show()

在此处输入图像描述

或者,您可以不理会pcolor范围,并修改imshow范围,但这会改变imshow图像的纵横比:

implot = ax.imshow(im, extent=[0, values.shape[1], 0, values.shape[0]])

p = ax.pcolor(values, alpha = 0.5, cmap='viridis')  

在此处输入图像描述


推荐阅读