画柱状图
导入库
import matplotlib.pyplot as plt
import numpy as np
利用函数:
bar(left, height, width=0.8, bottom=None, **kwargs)
left=柱子的下标列表
height=柱子高度
wideth=柱子宽度
还有一些别的参数
color=柱子的颜色
edgecolor=柱子边框颜色(若没有,系统默认没有边框)
linewidth=边框的宽度
lable=柱状图图例
举一个多个班级人数的例子:
# 创建一个的窗口
plt.figure()
# 柱子(班级)总数
n=6
# 6个柱子的数据
values = (52, 53, 60, 63, 49, 72)
# 柱子宽度
width=0.3
# 导入柱子下标
index = np.arange(n)
# 设置柱子数据
ax= plt.bar(index, values, width, color="red", edgecolor='blue', linewidth='1',label="classman")
# 显示图例
plt.legend(loc="best") # 上章有说明有关loc的意思
# 显示柱子
plt.show()
改变X,Y轴的数据
# X轴
plt.xlabel('class_num')
# Y轴
plt.ylabel('man')
# X轴数据更改
plt.xticks(index, ('class1', 'class2', 'class3', 'class4', 'class5', 'class6'))
# 添加标题
plt.title('eve class man')
添加子图
1:fig.add_subplot(221)
2:plt.subplot(2, 2, 1)
添加一张2行2列的子图,后面的1代表第一张图
# 创建一个的窗口
plt.figure()
# 这里加入子图
plt.subplot(2, 2, 1) #######
########
# 柱子(班级)总数
n=6
# 6个柱子的数据
values = (52, 53, 60, 63, 49, 72)
可以在一张表中添加多个图像
plt.subplot(2, 2, 2)
x = np.linspace(-1, 5, 20)
y1 = x + 1
plt.plot(x, y1)
plt.subplot(2, 2, 3)
x = np.linspace(-1, 5, 20)
y1 = x + 1
plt.plot(x, y1)
完整代码
import matplotlib.pyplot as plt
import numpy as np
# 创建一个的窗口
plt.figure()
# 这里加入子图
plt.subplot(2, 2, 1) # 子图1
# 柱子(班级)总数
n=6
# 6个柱子的数据
values = (52, 53, 60, 63, 49, 72)
# 柱子宽度
width=0.3
# 导入柱子下标
index = np.arange(n)
# 设置柱子数据
ax= plt.bar(index, values, width, color="red", edgecolor='blue', linewidth='1',label="classman")
# 显示图例
plt.legend(loc="best") # 上章有说明有关loc的意思
# 显示柱子
# X轴
plt.xlabel('class_num')
# Y轴
plt.ylabel('man')
# X轴数据更改
plt.xticks(index, ('class1', 'class2', 'class3', 'class4', 'class5', 'class6'))
# 添加标题
plt.title('eve class man')
plt.subplot(2, 2, 2) # 子图2
x = np.linspace(-1, 5, 20)
y1 = x + 1
plt.plot(x, y1)
plt.subplot(2, 2, 3) # 子图3
x = np.linspace(-1, 5, 20)
y1 = x + 1
plt.plot(x, y1)
# 显示图像
plt.show()