Nate
Nate

Reputation: 33

Adding text into bar-chart graph in Matplotlib (Python)

I need text at the x-axis in Matplotlib graph. I have:

import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7,8,9,10,11,12]
y=[5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9]

plt.bar(x,y, color='g')

plt.xlabel('x')
plt.ylabel('y')
plt.title("Max Temperature for Months")
plt.legend()
plt.show()

And my output is:

My graph

I don't know how to replace x=[ ] list with text (strings), it gives me error.

My desired graph is:

My desied graph

Upvotes: 1

Views: 1183

Answers (1)

Chuck
Chuck

Reputation: 3852

Use the plt.xticks() function as follows:

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]

plt.bar(x,y, color='g')

plt.xlabel('x')
plt.ylabel('y')

Generate some labels to go on your graph. The list of strings must be the same length as your x and y lists:

LABELS = ["M","w","E","R","T"]

Plot them with the following:

plt.xticks(x, LABELS)

plt.title("Max Temperature for Months")
plt.legend()
plt.show()

See example here: http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

Edit: For information on adjusting the location/orientation/position of your labels, see the matplotlib api documentation, and this question: matplotlib ticks position relative to axis.

Edit: Added Image: http://imgur.com/igjUGLb

Edit: To achieve the location and orientation that you need, you will find a great example in this question: Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother.

Implementing:

b = plt.bar(x,y, color='g')
xticks_pos = [0.5*patch.get_width() + patch.get_xy()[0] for patch in b]        
plt.xticks(xticks_pos, LABELS,rotation = 45)

gives: https://i.sstatic.net/arACh.jpg Hope that helps.

Upvotes: 3

Related Questions