【问题标题】:legend in sns.pairplot does not show completelysns.pairplot 中的图例未完全显示
【发布时间】:2020-12-29 12:08:46
【问题描述】:

我有一个 sns.pairplot,图例在轴外。无论我如何调整 bbox_to_anchor,除非我将图例的右侧放在轴内,否则图例的左侧会被切掉一点。

这是图例最初的位置:

我可以通过以下方式成功调整图例的位置:

g._legend.set_bbox_to_anchor((1, .53, .0, 0))

无论我如何移动图例,它总是被切断图例的同一小部分。这真的很奇怪。这是由于一些电话:

plt.subplots_adjust(hspace=0.02, wspace=0.04)    

以下是我调用来调整图例的所有命令:

g._legend.set_title('')
g._legend.set_bbox_to_anchor((1.01, .53, 0, 0))

#new_labels = ['Cluster 1', 'Cluster 2', 'Cluster 3'...]
new_labels = ['Cluster ' + str(i) for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)


for lh in g._legend.legendHandles: 
    lh.set_alpha(1)
    lh._sizes = [70] 

g._legend.borderpad=5

也不行……

【问题讨论】:

  • f.savefig('test.png', bbox_inches='tight')保存图
  • @PaulH 感谢您的 cmets,但问题仍然存在......
  • @XinNiu Cn 你试试这个fig.add_axes([0.1, 0.1, 0.6, 0.75]) 来为你的图表添加空间
  • @Karthik 感谢您的评论,但我使用 sns.pairplot 来创建图形。当我运行 g.add_axes() 时,它说该对象没有属性 add_axes()。
  • 设置bbox_to_anchor时,loc也需要设置。见seaborn relplot: how to control the location of the legend。在这种情况下,您可能需要g._legend._loc = 'upper left'(或2)见docs

标签: matplotlib seaborn legend


【解决方案1】:

我只是想出了另一个解决方案。只需在图例标签起作用后添加更多空间即可。

喜欢改代码:

new_labels = ['Cluster ' + str(i) for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

到:

new_labels = ['Cluster ' + str(i) + ' ' for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

【讨论】:

    【解决方案2】:

    您可以设置自己的图例。您可以使用plt.legend() 设置图例。如果您想删除原始图例,请启用ax._lengen.remove()

    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_theme(style="ticks")
    
    df = sns.load_dataset("penguins")
    ax = sns.pairplot(df, hue="species")
    # ax._legend.remove()
    
    plt.legend(['Adelie', 'Chinstrap', 'Gentoo'], bbox_to_anchor=(0.9, 0.6))
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多