【问题标题】:How do I add a colorbar to an image while saving it?如何在保存图像时向图像添加颜色条?
【发布时间】:2016-06-16 16:02:34
【问题描述】:

我有一个二维矩阵,比如img,我想使用'hot' 颜色图将其保存为图像。以下代码

import matplotlib.pyplot as plt

plt.imsave("out.jpg", img, cmap = 'hot')

允许我这样做。但是,我想将颜色条与图像一起保存,对我来说,大致了解每个像素的值是很重要的。假设我在右边有很多可用空间。

我知道这可以通过“简单”的方式完成,使用plt.imshow() 创建一个图形,使用plt.colorbar() 添加一个颜色条,然后使用plt.savefig() 保存它,但这也可以保存“灰色区域” " 围绕图形和颜色条分别出现。此外,如果涉及缩放,这与图形大小有关。我希望颜色条出现在图像上,并且生成的输出图像与矩阵大小相同。

此外,如果有人对将矩阵可视化为图像有任何其他建议(值不受限制),我们将不胜感激。

【问题讨论】:

    标签: python matplotlib data-visualization


    【解决方案1】:

    我不确定如何在您按照自己的意愿保存图像之前为其添加颜色条,我什至不确定这是否可能。但我可以为您提供一种绘制图像、添加颜色条并保存它的方法,但可以按照您想要的方式对其进行格式化。试试下面的方法

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize = (W,H)) # Your image (W)idth and (H)eight in inches
    # Stretch image to full figure, removing "grey region"
    plt.subplots_adjust(left = 0, right = 1, top = 1, bottom = 0)
    im = plt.imshow('out.jpg') # Show the image
    pos = fig.add_axes([0.93,0.1,0.02,0.35]) # Set colorbar position in fig
    fig.colorbar(im, cax=pos) # Create the colorbar
    plt.savefig('out.jpg')
    

    我不能保证在没有东西测试的情况下它会起作用,但它应该是你想要的正确方向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2019-08-22
      • 2016-10-18
      • 2020-05-08
      • 2017-11-20
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多