如何用美元标志和十进制格式化bar_label

发布于 2025-01-17 09:08:01 字数 667 浏览 2 评论 0原文

我需要在海洋小号上方显示数据。数字表示美元,我想将值25200显示为$ 25.2K

这是我当前用来显示下图的代码。

import seaborn as sns
import matplotlib.pyplot as plt

i = sns.barplot(ax = axes[1,0], x=lr_2021['decile'], y=np.round((lr_2021['NonCAT Severity']/1000),2), color = 'purple')
i.bar_label(axes[1,0].containers[0])

显示以下显示:

“在此处输入图像描述”

我尝试将以下内容添加到bar_label line:

i.bar_label(axes[1,0].containers["$",0, "K"])

该错误是。这可能吗?

I need to display the data above a seaborn barplot. The numbers represent dollars and I would like to display the value 25200 as $25.2k.

This is the code I currently use to display the below graph.

import seaborn as sns
import matplotlib.pyplot as plt

i = sns.barplot(ax = axes[1,0], x=lr_2021['decile'], y=np.round((lr_2021['NonCAT Severity']/1000),2), color = 'purple')
i.bar_label(axes[1,0].containers[0])

Which displays this:

enter image description here

I tried adding the following to the bar_label line:

i.bar_label(axes[1,0].containers["
quot;,0, "K"])

That error'd out however. Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天涯离梦残月幽梦 2025-01-24 09:08:01

如果您需要添加$前缀和K后缀,则fmt参数最简单:

i.bar_label(axes[1,0].containers[0], fmt='$%gK')

但是在这个在这种情况下,您还需要将值除以 1000。这对于 fmt 来说太复杂,因此可以通过 labels< 将 f 字符串应用于容器的 datavalues /代码>参数:

bars = axes[1,0].containers[0]
i.bar_label(bars, labels=[f'${value/1000:.1f}K' for value in bars.datavalues])

If you only need to add a $ prefix and K suffix, the fmt param is simplest:

i.bar_label(axes[1,0].containers[0], fmt='$%gK')

But in this case, you also need to divide the values by 1000. That's too complex for fmt, so instead apply an f-string to the container's datavalues via the labels param:

bars = axes[1,0].containers[0]
i.bar_label(bars, labels=[f'${value/1000:.1f}K' for value in bars.datavalues])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文