1

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

1
  • Can you accept my answer if it was helpful? Thanks Commented Jan 4, 2017 at 13:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Instead of xticks_pos, you could use plt.bar(..., align='center').
To define LABELS you could use import datetime, LABELS = [DT.datetime.strftime(DT.date(2001,xi,1), '%B') for xi in x].
@unutbu Great advice. Completely forgot about align. Much cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.