向条形标签添加逗号

Aja*_*hah 6 python matplotlib bar-chart seaborn plot-annotations

我一直在使用该ax.bar_label方法将数据值添加到条形图中。数字很​​大,例如143858918。如何使用该ax.bar_label方法向数据值添加逗号?我确实知道如何使用注释方法添加逗号,但如果可以使用bar_label,我不确定。是否可以使用fmt可用的关键字参数?

tdy*_*tdy 14

\n

是否可以使用 的fmt关键字参数ax.bar_label

\n
\n

是的,但仅限于 matplotlib 3.7+。在 3.7 之前,fmt仅接受%格式化程序(不支持逗号),因此labels需要f格式化容器的datavalues.

\n
    \n
  • 如果 matplotlib \xe2\x89\xa5 3.7,请使用fmt

    \n
    for c in ax.containers:\n    ax.bar_label(c, fmt=\'{:,.0f}\')  # \xe2\x89\xa5 3.7\n    #                   ^no f here (not an actual f-string)\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
  • 如果 matplotlib < 3.7,请使用labels

    \n
    for c in ax.containers:\n    ax.bar_label(c, labels=[f\'{x:,.0f}\' for x in c.datavalues])  # < 3.7\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
\n
\n

玩具示例:

\n
fig, ax = plt.subplots()\nax.bar([\'foo\', \'bar\', \'baz\'], [3200, 9025, 800])\n\n# \xe2\x89\xa5 v3.7\nfor c in ax.containers:\n    ax.bar_label(c, fmt=\'{:,.0f}\')\n
Run Code Online (Sandbox Code Playgroud)\n
# < v3.7\nfor c in ax.containers:\n    ax.bar_label(c, labels=[f\'{x:,.0f}\' for x in c.datavalues])\n
Run Code Online (Sandbox Code Playgroud)\n

\n