如何将货币格式添加到matplotlib.pyplot.text?

时间:2019-02-13 23:52:15

标签: python-3.x matplotlib

我想更改用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)

1 个答案:

答案 0 :(得分:0)

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

第一:只需在文本中添加字符串$

  • 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) 

enter image description here