python - 如何向 subplot2grid 添加颜色条

标签 python matplotlib subplot colormap

这应该非常简单,但由于某种原因我无法让它工作:

def plot_image(images, heatmaps):
    plt.figure(0)
    for i, (image, map) in enumerate(zip(images, heatmaps)):
        a = plt.subplot2grid((2,4), (0,i))
        a.imshow(image)
        a = plt.subplot2grid((2,4), (1,i))
        a.imshow(map)
        plt.colorbar(a, fraction=0.046, pad=0.04) 
    plt.show()

颜色条行中的值取自 here ,但我得到:

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

我正在绘制 2 x 4 的图像网格,并且我想在每个图像的右侧显示垂直颜色条,或者可能仅在网格中最右边的图像旁边显示垂直颜色条。

最佳答案

plt.colorbar 期望图像作为其第一个参数(或者通常是 ScalarMappable),而不是轴。

plt.colorbar(im, ax=ax, ...)

因此您的示例应为:

import numpy as np
import matplotlib.pyplot as plt

def plot_image(images, heatmaps):
    fig = plt.figure(0)
    for i, (image, map) in enumerate(zip(images, heatmaps)):
        ax = plt.subplot2grid((2,4), (0,i))
        im = ax.imshow(image)
        ax2 = plt.subplot2grid((2,4), (1,i))
        im2 = ax2.imshow(map)
        fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) 
        fig.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04) 
    plt.show()

a = [np.random.rand(5,5) for i in range(4)]
b = [np.random.rand(5,5) for i in range(4)]
plot_image(a,b)

enter image description here

关于python - 如何向 subplot2grid 添加颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167584/

相关文章:

python - django rest framework 过滤器忽略映射到枚举的 int 字段

python - BioPython 字母汤

python - 如何创建 Tkinter 主菜单

python - 带有多条轨迹的子图

python - Matplotlib;向子图添加圆圈 - 问题/困惑

python - 按组计算 Pandas Dataframe 中列表的重复项计数

python - pandas 列值和变量值字符串连接

python - Matplotlib 导航工具栏嵌入 pyqt5 窗口 - 重置原始 View 崩溃

matplotlib - 添加与第一个 y 轴相关的第二个 y 轴

MATLAB 子图不停留在页面的一侧