Seaborn向条形图添加百分号

2024-09-28 05:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将百分比(%)符号添加到条形图中的每个值中,但我不完全确定如何执行。我知道有一个get_text函数可以帮助您

g =  sns.catplot(
    data=df, 
    kind="bar",
    x="City", 
    y="Customers", 
    hue="Acquisition_Channel",
    ci="sd", 
    palette="dark", 
    alpha=.7,
    height=8,   
 )

g.set(ylim=(0, 100)) 
g.despine(right=False) 
g.set_xlabels("City") 
g.set_ylabels("Share of Customers vs. Total acquired Customers (%)")  
g.set_yticklabels("") 

ax=g.ax #annotate axis = seaborn axis

def annotateBars(row, ax=ax):
    for p in ax.patches:
        ax.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),

        ha='center', va='center', fontsize=12, color='gray', rotation=0, xytext=(0, 20),
        textcoords='offset points')

plot = df.apply(annotateBars, ax=ax, axis=1)



Tags: textcitydfget符号ax百分比center
1条回答
网友
1楼 · 发布于 2024-09-28 05:29:10

这里

ax.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),

您正在使用string % data,它不是特定于seaborn的,但通常在python中使用。如果要将文字%放在两倍(%%)的位置,例如:

print("%.0f%%" % 95)

输出

95%

如果您想了解更多信息,请阅读old string formatting in docs

相关问题 更多 >

    热门问题