#coding = utf-8
import matplotlib.pyplot as plt
import numpy as np
#配置信息,用来显示matplotlib中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
#用来 正常显示负号
plt.rcParams['axes.unicode_minus'] = False
#步骤一:创建数据
data = {
'dog':(48,'#7199cf'),
'cat':(45,'#4fc4aa'),
'lion':(120,'#e1a7a2')
}
#获取动物名称
names = list(data.keys())
#获取速度和颜色
speeds = [i[0] for i in data.values()]
colors = [i[1] for i in data.values()]
#设置x轴数据
x = np.arange(3)
#设置柱形图柱子宽度
bar_width = 0.3
#生成柱状图
bar = plt.bar(x,speeds,width=bar_width)
#绑定颜色值
for b,c in zip(bar,colors):
b.set_color(c)
#获取AxesSubplot
ax = plt.subplot()
#设置X 轴Y轴标题
ax.set_ylabel('speed km/h')
ax.set_xlabel('animal')
#设置数据位置
ax.set_xticks(x)
#显示动物名称
ax.set_xticklabels(names)
#设置画布标题
ax.set_title("图:动物速度表")
#为每个柱子添加数据
for x,d in zip(x,speeds):
plt.text(x,d,"{0}km/h".format(d),ha='center',va='bottom')
# 设置网格线
# plt.grid(linestyle="--")
#显示
plt.show()
结果如下: