代码之家  ›  专栏  ›  技术社区  ›  Filippo Bistaffa

将水平颜色条的大小与Seaborn中方形热图的宽度匹配

  •  0
  • Filippo Bistaffa  · 技术社区  · 7 年前

    我想在Seaborn制作一个方形热图,下面有颜色条。 以下是我使用的代码:

    #!/usr/bin/env python3
    
    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.rand(5,4)
    
    grid_kws = {"height_ratios": (.9, .05), "hspace": .5}
    f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
    
    ax = sns.heatmap(data,
                     ax=ax,
                     cbar_ax=cbar_ax,
                     annot=True,
                     square=True,
                     cbar_kws={ "orientation": "horizontal" })
    
    plt.savefig("heatmap.png")
    

    下面是输出: output

    我怎样才能将颜色条的大小与热图的大小相匹配?

    1 回复  |  直到 7 年前
        1
  •  1
  •   ImportanceOfBeingErnest    7 年前

    您可以使用第二个或第三个选项 my answer positioning the colorbar 。因为对于一个海生的阴谋来说,如何做到这一点并不明显。

    使用子批次

    我们可以直接创建两行子图,一行用于图像,另一行用于颜色栏,正如在问题中所做的那样,我们只需要确保图形大小水平挤压绘图,而不是垂直挤压绘图。在这种情况下,尝试 figsize=(3,5) .

    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.rand(5,4)
    
    grid_kws = {"height_ratios": (.9, .05), "hspace": .5}
    fig, (ax, cbar_ax) = plt.subplots(2, figsize=(3,5), gridspec_kw=grid_kws)
    
    ax = sns.heatmap(data,
                     ax=ax,
                     cbar_ax=cbar_ax,
                     annot=True,
                     square=True,
                     cbar_kws={ "orientation": "horizontal" })
    
    #plt.savefig("heatmap.png")
    plt.show()
    

    enter image description here

    使用轴分割器

    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    data = np.random.rand(5,4)
    
    fig, ax = plt.subplots()
    
    divider = make_axes_locatable(ax)
    cbar_ax = divider.new_vertical(size="5%", pad=0.5, pack_start=True)
    fig.add_axes(cbar_ax)
    ax = sns.heatmap(data,
                     ax=ax,
                     cbar_ax=cbar_ax,
                     annot=True,
                     square=True,
                     cbar_kws={ "orientation": "horizontal" })
    
    
    #plt.savefig("heatmap.png")
    plt.show()
    

    enter image description here