首页 > 解决方案 > Seaborn 中的自定义图表格式

问题描述

我在 seaborn 中有一个简单的计数图。

代码是:

ax = sns.countplot(x="days", data=df,color ='cornflowerblue')
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
ax.set(xlabel='days', ylabel='Conversions')
ax.set_title("Days to Conversion")
for p in ax.patches:
    count = p.get_height()
    x = p.get_x() + p.get_width()/1.25
    y = p.get_height()*1.01
    ax.annotate(count, (x, y),ha='right')

产生:

在此处输入图像描述

我试图让图表更“漂亮”。具体来说,我想提高轮廓的高度,这样它就不会越过第一个条上的计数,并使计数以条的小空间居中。无法让它工作。

请指导。

标签: pythonseaborn

解决方案


要设置标签,在最新的 matplotlib 版本(3.4.2)中,有一个新功能bar_label()可以处理定位。在旧版本中,您可以使用您的代码,但使用x = p.get_x() + p.get_width()/2并设置ax.text(..., ha='center').

为了给标签腾出空间,可以通过添加额外的边距ax.margins(y=0.1)

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('tips')
ax = sns.countplot(x="day", data=df, color='cornflowerblue')
ax.tick_params(axis='x', labelrotation=90)
ax.bar_label(ax.containers[-1])
ax.margins(y=0.1)
plt.tight_layout()
plt.show()

sns.countplot 带标签


推荐阅读