如何更改海洋计数图中图例的位置?

时间:2020-05-13 17:51:51

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

下面的代码生成带有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))

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

enter image description here

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

2 个答案:

答案 0 :(得分:1)

我没有您要尝试的数据,但是https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.legend.html中的plt.legend(loc='lower left')应该可以完成任务(顺便说一句,现在您可以使用它,也许您想lower right)。

答案 1 :(得分:0)

您可能还想让图例使用

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