【问题标题】:Python matplotlib - how to move colorbar without resizing the heatmap?Python matplotlib - 如何在不调整热图大小的情况下移动颜色条?
【发布时间】:2013-10-30 10:13:38
【问题描述】:

您好,我有以下命令。

在网格中为热图指定子图轴:

ax4 = plt.subplot2grid((3, 4), (1, 3), colspan=1, rowspan=1)

在这个轴上创建我的热图:

heatmap = ax4.pcolor(data, cmap=mycm, edgecolors = 'none', picker=True)

根据其他子图将图向右移动以使其在轴中居中:

box = ax4.get_position()
ax4.set_position([box.x0*1.05, box.y0, box.width * 1.05, box.height])

显示没有填充的颜色条

fig.colorbar(heatmap, orientation="vertical")

但是这会导致:

注意颜色条位于热图的顶部。

如果我使用 pad 关键字,我可以移动颜色条,使其不与热图重叠,但这会减小绘图区域的宽度,即:

如何使绘图区域保持相同的宽度,并且只在该区域之外放置颜色条?

谢谢!

【问题讨论】:

    标签: python matplotlib position heatmap colorbar


    【解决方案1】:

    您可以将colorbar into it's own axis 直接设置为该轴的大小和位置。我在下面包含了一个示例,它为您现有的代码添加了另一个轴。如果此图包含许多绘图和彩条,您可能希望使用gridspec 将它们全部添加。

    import matplotlib.pylab as plt
    from numpy.random import rand
    
    data = rand(100,100)
    mycm = plt.cm.Reds
    
    fig = plt.figure()
    ax4 = plt.subplot2grid((3, 4), (1, 3), colspan=1, rowspan=1)
    
    heatmap = ax4.pcolor(data, cmap=mycm, edgecolors = 'none', picker=True)
    
    box = ax4.get_position()
    ax4.set_position([box.x0*1.05, box.y0, box.width, box.height])
    
    # create color bar
    axColor = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
    plt.colorbar(heatmap, cax = axColor, orientation="vertical")
    plt.show()
    

    【讨论】:

    • 谢谢,我以前看过这个,但还是有问题。但是您的回答提示我再试一次,效果很好,谢谢!
    猜你喜欢
    • 2020-05-07
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多