【问题标题】:How to add currency format to matplotlib.pyplot.text? [duplicate]如何将货币格式添加到 matplotlib.pyplot.text? [复制]
【发布时间】:2019-07-07 22:31:31
【问题描述】:

我想更改使用 matplotlib.pyplot.text 创建的文本的格式 - 我将在条形图中的每个条形上方添加文本。但我不知道怎么做。我尝试了question 中建议的方法,能够更改 y 轴上的格式,但文本框没有成功。

Example image

这是链接问题中使用的方法(我也用于我的 y 轴):

fig, ax = plt.subplots(1, 1, figsize=(8, 5))
fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

这是我用来创建文本的代码:

for i in range(len(cost_tbl)):
    ax.text(i-0.2, cost_tbl[i, 2]+18000, str(int(cost_tbl[i, 2])), rotation=60)

【问题讨论】:

  • '${x:,.0f}'.format(x=int(cost_tbl[i, 2]))

标签: python-3.x matplotlib


【解决方案1】:

您有两种选择。由于您没有提供示例数据,因此我将在下面进行解释。

首先:只需将字符串$ 添加到您的文本中

  • ax.text(i, height[i]+100000, '$'+str(int(height[i])), rotation=60)

第二使用你的fmt = '${x:,.0f}' 没有 x

  • ax.text(i, height[i]+100000, '${:,.0f}'.format(height[i]), rotation=60)

import matplotlib.ticker as mtick
import numpy as np; np.random.seed(10)

fig, ax = plt.subplots(1, 1, figsize=(8, 5))
height = np.random.randint(100000, 500000, 10)
plt.bar(range(10), height)

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

for i in range(10):
#     ax.text(i, height[i]+5, '$'+str(int(height[i])), rotation=60)
    ax.text(i, height[i]+100000, '${:,.0f}'.format(height[i]), rotation=60)

plt.ylim(0, max(height)*1.5) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多