【问题标题】:How to change the location of a legend in seaborn countplot?如何更改 seaborn countplot 中图例的位置?
【发布时间】:2020-08-30 01:12:51
【问题描述】:

下面的代码会生成一个带有 seaborn 的计数图并注释百分比:

ax = sns.countplot(y=target_column, data=data, hue=target_column)
plt.title(f'Distribution of {target_column}')
plt.xlabel('Number of occurrences')

total = len(data[target_column])
for p in ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_width()/total)
    x = p.get_x() + p.get_width() + 0.02
    y = p.get_y() + p.get_height()/2
    ax.annotate(percentage, (x, y))

我想添加一个图例,我知道有色相参数,但结果是图例框与实际的我的条和百分比注释重叠:

如何将图例的位置更改为绘图的右下角?

【问题讨论】:

    标签: python python-3.x matplotlib seaborn legend


    【解决方案1】:

    我没有你的数据可供尝试,但plt.legend(loc='lower left')https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.legend.html 一样应该可以完成这项工作(顺便说一句,这就是你现在拥有的数据,也许你想要lower right)。

    【讨论】:

      【解决方案2】:

      您可能还想让图例使用

      在空间方面选择最佳位置
      ax = sns.countplot(y=target_column, data=data, hue=target_column)
      ax.legend(loc='best')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 2019-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        相关资源
        最近更新 更多