使用新的f-string格式样式的Matplotlib条形图标签

6
自从 matplotlib 3.4.0 版本起,Axes.bar_label 方法可以用来给柱状图添加标签。但是,标签格式选项使用的是旧样式格式化,例如:fmt='%g'
如何使其与新样式格式化一起工作,以便进行百分比、千位分隔符等操作:'{:,.2f}', '{:.2%}', ...
我首先想到的是从 ax.containers 中获取初始标签,然后重新格式化它们,但这也需要适用于不同的柱状结构、不同格式的分组柱状图等。

FYI,在 matplotlib 3.7+ 中,fmt 现在支持 {} 样式的格式化字符串。 - tdy
1个回答

17

如何使得 bar_label 支持新样式的格式化,如百分号、千位分隔符等?

  • 从 matplotlib 3.7 开始

    fmt 参数现在直接支持基于 {} 的格式化字符串,例如:

    # >= 3.7
    plt.bar_label(bars, fmt='{:,.2f}')
    #                       ^no f here (not an actual f-string)
    
  • 在 matplotlib 3.7 之前的版本中

    fmt 参数不支持基于 {} 的格式字符串,因此请使用 labels 参数。使用 f-string 格式化柱状图容器的 datavalues,并将其设置为 labels,例如:

  • # < 3.7
    plt.bar_label(bars, labels=[f'{x:,.2f}' for x in bars.datavalues])
    

示例:

  • 千位分隔符标签


bars = plt.bar(list('ABC'), [12344.56, 23456.78, 34567.89])

# >= v3.7
plt.bar_label(bars, fmt='${:,.2f}')
# < v3.7
plt.bar_label(bars, labels=[f'${x:,.2f}' for x in bars.datavalues])

  • 百分比标签

    bars = plt.bar(list('ABC'), [0.123456, 0.567890, 0.789012])
    
    # >= 3.7
    plt.bar_label(bars, fmt='{:.2%}')  # >= 3.7
    
    # < 3.7
    plt.bar_label(bars, labels=[f'{x:.2%}' for x in bars.datavalues])
    

  • 堆叠百分比标签

    x = list('ABC')
    y = [0.7654, 0.6543, 0.5432]
    
    fig, ax = plt.subplots()
    ax.bar(x, y)
    ax.bar(x, 1 - np.array(y), bottom=y)
    
    # now 2 bar containers: white labels for blue bars, black labels for orange bars
    colors = list('wk')
    
    # >= 3.7
    for bars, color in zip(ax.containers, colors):
        ax.bar_label(bars, fmt='{:.1%}', color=color, label_type='center')
    
    # < 3.7
    for bars, color in zip(ax.containers, colors):
        labels = [f'{x:.1%}' for x in bars.datavalues]
        ax.bar_label(bars, labels=labels, color=color, label_type='center')
    


  • 网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接