代码:
import matplotlib.pyplot as plt
import numpy as np
plt.rcdefaults() #恢复plt的各项默认设置
fig, ax = plt.subplots() #返回一个包含figure和axes对象的元组,不过我们一般使用到的是ax
'''example data'''
people = ('y1', 'y2', 'y3', 'y4', 'y5')
y_pos = np.arange(len(people)) #确定纵坐标及其项数
performance = 3 + 10 * np.random.rand(len(people)) #由随机数函数得到各项的值,绘图时可自行设定
error = np.random.rand(len(people)) #这个函数我也没弄懂,欢迎大家评论区解释
ax.barh(y_pos, performance, xerr=error, align='center',
color='r', ecolor='black')
'''
y_pos:纵轴的项
performance:各项的值
可选参数:
height: bars 的高度
left: bars 左边缘 x 轴坐标值
color: bars 颜色
edgecolor: bars 边缘颜色
linewidth: bar 边缘宽度;None 表示默认宽度;0 表示不 i 绘制边缘
xerr: 若不为 None,将在 bar 图上生成 errobars
yerr: 若不为 None,将在 bar 图上生成 errobars
ecolor: 指定 errorbar 颜色
capsize: 指定 errorbar 的顶部(cap)长度
align: edge (默认) | center:edge以底部为准对齐;center以 y 轴作为中心
log: [False|True] False (默认),若为 True,使用 log 坐标
'''
ax.set_yticks(y_pos) #保证纵轴标签的正常显示
ax.set_yticklabels(people) #保证纵轴标签的展示
ax.invert_yaxis() # 纵坐标标签从上到下排列(可根据本例注释本函数查看)
ax.set_xlabel('横轴',fontproperties='SimHei',fontsize=20) #横坐标标签
#ax.set_xlabel('hengzhou') 全英文轴名表示
ax.set_ylabel('纵轴',fontproperties='SimHei',fontsize=20) #纵坐标标签
ax.set_title('图名',fontproperties='SimHei',fontsize=20) #图名
plt.show() #展示
运行结果:
本文代码来自点击这里,笔者只是加入了部分注释。水平有限,如有不足请大家多多指正。