matplotlib 具有新f字符串格式样式的条形标签

bweufnob  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(107)

从matplotlib 3.4.0开始,Axes.bar_label方法允许标记条形图。
但是,标签格式选项适用于旧格式,例如fmt='%g'
我如何使它与新的格式,将允许我做的事情,如百分比,千分隔符等工作:'{:,.2f}', '{:.2%}', ...
我想到的第一件事是以某种方式从ax.containers中获取初始标签,然后重新格式化它们,但它也需要适用于不同的条形图结构,不同格式的分组条形图等。

bt1cpqcv

bt1cpqcv1#

如何让bar_label使用新的格式,如百分比,千位分隔符等?

*自matplotlib 3.7起

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

  1. # >= 3.7
  2. plt.bar_label(bars, fmt='{:,.2f}')
  3. # ^no f here (not an actual f-string)

*matplotlib 3.7之前

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

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

示例如下:

*千个分隔符标签

  1. bars = plt.bar(list('ABC'), [12344.56, 23456.78, 34567.89])
  2. # >= v3.7
  3. plt.bar_label(bars, fmt='${:,.2f}')
  1. # < v3.7
  2. plt.bar_label(bars, labels=[f'${x:,.2f}' for x in bars.datavalues])

*标签百分比

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

*堆叠百分比标签

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

展开查看全部

相关问题