【问题标题】:Seaborn Heatmap Colorbar Custom LocationSeaborn 热图颜色条自定义位置
【发布时间】:2021-07-06 05:06:27
【问题描述】:

鉴于此热图:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)

我想将颜色条放在具有自定义大小的自定义位置(每个轴/绘图坐标)。 具体来说,我希望它在左上角(热图之外)水平放置,尺寸较小(但尚未定义)。这可能吗?我知道有一般的位置参数,但那些不允许我想做的事情。我也知道我可以用plt.colorbar() 定义一个单独的颜色条,但我也不知道如何自定义它的位置。

提前致谢!

【问题讨论】:

    标签: matplotlib seaborn colorbar


    【解决方案1】:

    您可以使用"inset axes" 为颜色条创建一个与子图完美搭配的斧头。在this tutorial example 中,“cax”是颜色条的“ax”。在seaborn的heatmap中,cbar_ax是colorbar的放置位置(当cbar_ax没有给出时,matplotlib选择默认位置)。 cbar_kw 可以为颜色条设置额外的关键字,例如设置水平方向。

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    import numpy as np; np.random.seed(0)
    import seaborn as sns; sns.set_theme()
    
    uniform_data = np.random.rand(10, 12)
    fig, ax = plt.subplots()
    cax = inset_axes(ax,
                     width="40%",  # width: 40% of parent_bbox width
                     height="10%",  # height: 10% of parent_bbox height
                     loc='lower left',
                     bbox_to_anchor=(0, 1.1, 1, 1),
                     bbox_transform=ax.transAxes,
                     borderpad=0,
                     )
    sns.heatmap(uniform_data, ax=ax, cbar_ax=cax, cbar_kws={'orientation': 'horizontal'} )
    plt.subplots_adjust(top=0.8) # make room to fit the colorbar into the figure
    plt.show()
    

    【讨论】:

    • 我可能应该更新我所看到的,但在我的实际热图中,标题现在附加到颜色条上,颜色条似乎需要旋转 90 度并拉伸另一种方式。这些容易解决吗?我猜标题与错误的轴相关联,尽管我正在做 plt.title。
    • 你需要ax.set_title来设置标题。您使用的是最新的 seaborn 版本 0.11.1 吗?我的示例代码在您的环境中工作吗?
    • 做到了。当然可以。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2020-06-21
    • 2020-10-21
    • 1970-01-01
    • 2018-05-07
    • 2020-09-28
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多