效果如图:
import matplotlib.pyplot as plt
import numpy as np
import os
import random
Fixing random state for reproducibility 循环使用
plt.rcdefaults()
创建一个图形和一个子图
fig, ax = plt.subplots()
Example data
people = (‘华东区’, ‘华南区’, ‘华北区’, ‘华西区’, ‘华中区’)
y_pos = np.arange(len(people))
x_pos = [230, 40, 61, 80, 100]
获取柱状图所有的柱状图对象
bars = ax.barh(y_pos,x_pos, align=‘center’,color=[‘r’,‘g’,‘b’,‘y’,‘r’], ecolor=‘black’)
循环设置每个柱状图的长度
for bar in bars:
w = bar.get_width()
# ax.text(“高度”,“坐标”,“标签内容”,ha=‘left’,va=‘center’)这样。
ax.text(w,bar.get_y()+bar.get_height()/2,’%d’%int(w),ha=‘right’,va=‘center’,rotation=0)
ax.set_yticks(y_pos)
ax.set_yticklabels(people, fontproperties=“SimSun”)
people 从上到下显示
ax.invert_yaxis()
x轴的名字
ax.set_xlabel(‘销售额’, fontproperties=“SimSun”)
图形的tittle
ax.set_title(‘地区’, fontproperties=“SimSun”)
show之前保存 show方法之后,这个画布就结束了
plt.savefig(os.path.abspath(os.curdir)+os.sep+str(random.randint(1, 10000)))
plt.show()