1

I want to change the format of the text created with matplotlib.pyplot.text - That I'm adding the text above each bar in a bar plot. But I dont know how. I have tried the approach suggested in this question, was able to change the format on the y axis, but had no success with the text boxes.

Example image

This is the method used in the linked question (which I also used for my y axis):

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

And this is code that I'm using to create the text:

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 Answers1

1

You have two options to do it. I will explain below with a sample data since you did not provide one.

First: Simply adding a string $ to your text

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

Second Using your fmt = '${x:,.0f}' without 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

Sheldore
  • 37,862
  • 7
  • 57
  • 71