首页 > 解决方案 > Seaborn catplot 中是否有一个参数来显示零值的条形图?

问题描述

在此处输入图像描述

我正在使用 Seaborn 的 catplot 创建此图,以根据复杂性比较每个 x 值的错误率。我知道在某些情况下错误率为零,因此没有条形表示它,但有没有办法在图表中显示?

g = sns.catplot(
    data=df, kind="bar",
    x="x", y="incorrect_score", 
    alpha=.7, hue="complexity",
    ci= False
)
g.despine(left=False)
g.set(ylim=(0, 0.9))
g.set_axis_labels("", "Error")
plt.show()

标签: pythonseaborn

解决方案


可能最简单的方法是在条形顶部显示数字:

def autolabel(rects, fmt='.2f'):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        rect.axes.annotate(f'{{:{fmt}}}'.format(height),
                           xy=(rect.get_x()+rect.get_width()/2., height),
                           xytext=(0, 3), textcoords='offset points',
                           ha='center', va='bottom')

g = sns.catplot(
    data=df, kind="bar",
    x="x", y="incorrect_score", 
    alpha=.7, hue="complexity",
    ci= False
)
g.despine(left=False)
g.set(ylim=(0, 0.9))
g.set_axis_labels("", "Error")

autolabel(g.ax.patches)
plt.show()

在此处输入图像描述

或者,如果您愿意,可以在条形为零时显示标签:

autolabel([rect for rect in g.ax.patches if rect.get_height()==0.0])

在此处输入图像描述


推荐阅读