导入包
import numpy as np
import matplotlib.pyplot as plt
准备数据
X = ('2011','2012','2013','2014','2015','2016','2017','2018')
per1 = [10,9,8,7,6,4,2,1]
per2 = [5,9,2,7,9,4,4,1]
设置字体支持中文
plt.rcParams['font.sans-serif'] = ['SimSun']
创建图形
fig,axis=plt.subplots()
定义条形图在横坐标上的分类位置
X_pos = np.arange(len(X))
定义图形的宽度
barwidth = 0.3
定义图形的透明度
opacity = 0.8
绘制第一个柱状图
bar1 = plt.bar(X_pos,per1,
barwidth,
alpha=opacity,
color='b',
label='per1')
绘制第二个柱状图
bar2 = plt.bar(X_pos+barwidth,
per2,
barwidth,
alpha=opacity,
color='r',
label='per2')
给横坐标命名
plt.xlabel('年份')
给纵坐标命名
plt.ylabel('数量')
添加标题
plt.title('数量对比图')
横坐标转为年份
plt.xticks(X_pos+barwidth,X)
添加图例
plt.legend()
展示图形结果
plt.show()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f2a8ef39062491b8be89c4e5c18ab35a.png)
附完整代码
import numpy as np
import matplotlib.pyplot as plt
X = ('2011','2012','2013','2014','2015','2016','2017','2018')
per1 = [10,9,8,7,6,4,2,1]
per2 = [5,9,2,7,9,4,4,1]
plt.rcParams['font.sans-serif'] = ['SimSun']
fig,axis=plt.subplots()
X_pos = np.arange(len(X))
barwidth = 0.3
opacity = 0.8
bar1 = plt.bar(X_pos,per1,
barwidth,
alpha=opacity,
color='b',
label='per1')
bar2 = plt.bar(X_pos+barwidth,
per2,
barwidth,
alpha=opacity,
color='r',
label='per2')
plt.xlabel('年份')
plt.ylabel('数量')
plt.title('数量对比图')
plt.xticks(X_pos+barwidth,X)
plt.legend()
plt.show()