简体   繁体   中英

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:

我的图

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

My desired graph is:

我想要的图

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://imgur.com/a/78Esz Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM