Kon*_*tin 6 python matplotlib bar-chart plot-annotations
从matplotlib 3.4.0开始,Axes.bar_label方法允许标记条形图。
但是,标签格式选项适用于旧式格式,例如fmt='%g'
我怎样才能使它与新的样式格式一起工作,使我能够执行百分比、千位分隔符等操作: '{:,.2f}', '{:.2%}', ...
我首先想到的是以某种方式获取初始标签ax.containers,然后重新格式化它们,但它还需要适用于不同的条形结构、具有不同格式的分组条形等等。
tdy*_*tdy 17
如何使用
bar_label百分比、千位分隔符等新样式格式?
从 matplotlib 3.7 开始
该fmt参数现在直接支持{}基于格式字符串,例如:
# >= 3.7
plt.bar_label(bars, fmt='{:,.2f}')
# ^no f here (not an actual f-string)
Run Code Online (Sandbox Code Playgroud)
matplotlib 3.7 之前的版本
该fmt参数不支持{}基于格式字符串,因此请使用该labels参数。datavalues使用 f 字符串格式化 bar 容器并将其设置为labels,例如:
# < 3.7
plt.bar_label(bars, labels=[f'{x:,.2f}' for x in bars.datavalues])
Run Code Online (Sandbox Code Playgroud)
例子:
千位分隔符标签
bars = plt.bar(list('ABC'), [12344.56, 23456.78, 34567.89])
# >= v3.7
plt.bar_label(bars, fmt='${:,.2f}')
Run Code Online (Sandbox Code Playgroud)
# < v3.7
plt.bar_label(bars, labels=[f'${x:,.2f}' for x in bars.datavalues])
Run Code Online (Sandbox Code Playgroud)
百分比标签
bars = plt.bar(list('ABC'), [0.123456, 0.567890, 0.789012])
# >= 3.7
plt.bar_label(bars, fmt='{:.2%}') # >= 3.7
Run Code Online (Sandbox Code Playgroud)
# < 3.7
plt.bar_label(bars, labels=[f'{x:.2%}' for x in bars.datavalues])
Run Code Online (Sandbox Code Playgroud)
堆叠百分比标签
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')
Run Code Online (Sandbox Code Playgroud)
# < 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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7179 次 |
| 最近记录: |