如何在seaborn countplot中更改图例的位置?

7 浏览
0 Comments

如何在seaborn countplot中更改图例的位置?

以下是使用seaborn生成带有注释百分比的countplot的代码:

ax = sns.countplot(y=target_column, data=data, hue=target_column)
plt.title(f'{target_column}的分布')
plt.xlabel('出现次数')
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))
ax.legend(loc='lower right')

我想添加一个图例,我知道有hue参数,但结果是图例框重叠在实际的柱状图和百分比注释上。如何将图例的位置更改为图的右下角?

0
0 Comments

问题出现的原因是想要改变seaborn countplot中图例(legend)的位置。

解决方法是使用ax.legend(loc='best')来让图例选择最佳位置。

0
0 Comments

问题的出现原因是用户想要在seaborn countplot中更改图例(legend)的位置。用户尝试使用plt.legend(loc='lower left')来更改图例的位置,但未成功。

解决方法是根据用户的需求,将lower left改为lower right,然后再次运行代码即可。

0