【问题标题】:Seaborn add percentage sign to barplotSeaborn 将百分比符号添加到条形图
【发布时间】:2021-06-02 20:05:00
【问题描述】:

我正在尝试将百分比 (%) 符号添加到我的条形图中的每个值,但我不完全确定该怎么做。我知道有 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)


【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    这里

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2022-01-09
      • 2017-11-27
      • 1970-01-01
      • 2016-06-16
      • 2021-07-17
      相关资源
      最近更新 更多