【问题标题】:Adjusting python pcolor chart over the picture在图片上调整 python pcolor 图表
【发布时间】:2021-09-22 19:39:40
【问题描述】:

我想在图片上放一个 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 图表大小?

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

提前感谢您的任何想法。

【问题讨论】:

    标签: python image matplotlib


    【解决方案1】:

    您需要修复图像或 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')  
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      相关资源
      最近更新 更多