代码之家  ›  专栏  ›  技术社区  ›  Jordan

如何将Seaborn数据标签更改为显示两位小数

  •  1
  • Jordan  · 技术社区  · 8 年前

    如何在Seaborn Barplot(或任何与此相关的绘图)中编码数据标签以显示两位小数?

    我从这篇文章中学到了如何显示数据标签: Add data labels to Seaborn factor plot

    但我不能让标签显示数字。

    参见下面的示例代码:

    #make the simple dataframe
    married = ['M', "NO DATA", 'S']
    percentage = [68.7564554, 9.35558, 21.8879646]
    df = pd.DataFrame(married, percentage)
    df.reset_index(level=0, inplace=True)
    df.columns = ['percentage', 'married']
    
    #make the bar plot
    sns.barplot(x = 'married', y = 'percentage', data = df)
    plt.title('title')
    plt.xlabel('married')
    plt.ylabel('Percentage')
    
    #place the labels
    ax = plt.gca()
    y_max = df['percentage'].value_counts().max() 
    ax.set_ylim(1)
    for p in ax.patches:
        ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' % 
        int(p.get_height()), 
            fontsize=12, color='red', ha='center', va='bottom')
    

    谢谢你的帮助

    1 回复  |  直到 8 年前
        1
  •  1
  •   Scott Boston    8 年前

    使用,字符串格式 https://docs.python.org/3.4/library/string.html#format-specification-mini-language :

    married = ['M', "NO DATA", 'S']
    percentage = [68.7564554, 9.35558, 21.8879646]
    df = pd.DataFrame(married, percentage)
    df.reset_index(level=0, inplace=True)
    df.columns = ['percentage', 'married']
    
    #make the bar plot
    sns.barplot(x = 'married', y = 'percentage', data = df)
    plt.title('title')
    plt.xlabel('married')
    plt.ylabel('Percentage')
    
    #place the labels
    ax = plt.gca()
    y_max = df['percentage'].value_counts().max() 
    ax.set_ylim(1)
    for p in ax.patches:
        ax.text(p.get_x() + p.get_width()/2., p.get_height(), '{0:.2f}'.format(p.get_height()), 
            fontsize=12, color='red', ha='center', va='bottom')
    

    输出: enter image description here