一. matplotlib 简介
Matplotlib是一个Python 2D绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形。
Matplotlib试图让简单的事情变得更简单,让无法实现的事情变得可能实现。 只需几行代码即可生成绘图,直方图,功率谱,条形图,错误图,散点图等。
二. matplotlib 画图常见属性
1. 线条属性
-
color:颜色
‘b’ blue ‘g’ green ‘y’ yellow ‘r’ red ‘w’ white ‘k’ black -
linestyle:线条风格
‘-’ solid line style ‘–’ dashed line style ‘-.’ dash-dot line style ‘:’ dotted line style -
linewidth:线宽
-
marker:标记
‘.’ point marker ‘,’ pixel marker ‘o’ circle marker ‘v’ triangle_down marker import numpy as np import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y = np.sin(x)ax.plot(x,y, color = 'r', linewidth = 1, linestyle = '-', marker = 'o')plt.show()
运行结果:
2. 坐标轴刻度,坐标轴范围,坐标轴标签和图例
-
坐标轴刻度和范围
- set_xticks:设置x轴刻度
- set_yticks:设置y轴刻度
- set_xlim:设置x轴范围
- set_ylim:设置y轴范围
import numpy as np import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y = np.sin(x)ax.plot(x,y)ax.set_xticks(np.arange(-10, 11, 1))ax.set_yticks(np.arange(-2, 3, 1))ax.set_xlim(-10, 10)ax.set_ylim(-2, 2)plt.show()
运行结果:
-
坐标轴标签和图例
- set_xlabel:设置x轴标签
- set_xlabel:设置y轴标签
- plot方法的label属性可以设置图例
- legend:显示图例
import numpy as np import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y1 = np.sin(x)y2 = np.cos(x)ax.plot(x,y1, label = 'sin')ax.plot(x, y2, label = 'cos')ax.set_xlabel("x")ax.set_ylabel("y")ax.legend()plt.show()
运行结果:
3. 文本和注释
-
text:设置文本
import numpy as np import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y = np.sin(x)ax.plot(x, y)ax.set_ylim(-2, 3)ax.text(x = 0, y = 1.5, s = 'text')plt.show()
运行结果:
-
annotate:设置注释
import numpy as np import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y = np.sin(x)ax.plot(x, y)ax.set_ylim(-2, 3)ax.annotate('zero_point', xy = (0, 0), xytext = (0, 1), arrowprops= {'headwidth':4,'width':2})plt.show()
运行结果:
三. matplotlib 绘制多个子图
matplotlib的图像位于Figure对象中,空的Figure对象不能绘图,还需要在Figure对象上添加子图才能真正绘图,matplotlib中提供了两种方法可以添加子图。
1. add_subplot
import numpy as np
import matplotlib.pyplot as pltif __name__ == '__main__':fig = plt.figure(figsize= (6,4))ax1 = fig.add_subplot(2, 2, 1)ax2 = fig.add_subplot(2, 2, 2)ax3 = fig.add_subplot(2, 2, 3)ax4 = fig.add_subplot(2, 2, 4)x = np.linspace(-10, 10, 200)y1 = np.sin(x)y2 = np.cos(x)y3 = np.tan(x)y4 = 2 * x + 10ax1.plot(x, y1)ax2.plot(x, y2)ax3.plot(x, y3)ax4.plot(x, y4)plt.show()
运行结果:
2. subplots
import numpy as np
import matplotlib.pyplot as pltif __name__ == '__main__':fig,axes = plt.subplots(2, 2, figsize= (6,4))x = np.linspace(-10, 10, 200)y = np.sin(x)for i in range(0, 2):for j in range(0, 2):axes[i][j].plot(x,y)plt.show()
运行结果:
四. matplotlib 绘制常见图形
1. 折线图
将每个数据点连接起来就构成折线图,折线图可以直观显示数据的值和变化趋势。
import numpy as np
import matplotlib.pyplot as plt#中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseif __name__ == '__main__':fig = plt.figure(figsize=(15, 8))ax = fig.add_subplot()x = np.linspace(-10, 10, 200)y = np.sin(x)ax.plot(x, y, label='sin')ax.legend()plt.show()
运行结果:
2. 散点图
散点图一般用于分析两个变量之间是否存在某种关联。
import numpy as np
import matplotlib.pyplot as plt#中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseif __name__ == '__main__':fig = plt.figure(figsize=(15, 8))ax = fig.add_subplot()x = [225.98, 247.07, 253.14, 457.85, 241.58, 301.01, 20.67, 288.64,163.56, 120.06, 207.83, 342.75, 147.9, 53.06, 224.72, 29.51,21.61, 483.21, 245.25, 399.25, 343.35]y = [196.63, 203.88, 210.75, 372.74, 202.41, 247.61, 24.9, 239.34,140.32, 104.15, 176.84, 288.23, 128.79, 49.64, 191.74, 33.1,30.74, 400.02, 205.35, 330.64, 283.45]ax.scatter(x, y)plt.show()
运行结果:
2. 直方图
直方图由一系列高度不等的纵向条纹或线段表示数据分布的情况,一般用来展示数据的分布。
import numpy as np
import matplotlib.pyplot as plt#中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseif __name__ == '__main__':fig = plt.figure(figsize=(15, 8))ax = fig.add_subplot()students_score = [22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27, 67]ax.hist(students_score, bins=[0, 20, 40, 60, 80, 100], density=True)ax.set_xlabel("分数")ax.set_ylabel("数量")ax.set_xticks([0, 20, 40, 60, 80, 100])plt.show()
运行结果:
3. 柱状图
柱状图使用柱状显示数据,能够一眼看出各个数据的大小,比较数据之间的差别。
import numpy as np
import matplotlib.pyplot as plt#中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseif __name__ == '__main__':fig = plt.figure(figsize=(15, 8))ax = fig.add_subplot()movie_name = ['雷神3:诸神黄昏', '正义联盟', '东方快车谋杀案', '寻梦环游记', '全球风暴', '降魔传','追捕', '七十七天', '密战', '狂兽', '其它']# 横坐标x = range(len(movie_name))# 票房数据y = [73853, 57767, 22354, 15969, 14839, 8725, 8716, 8318, 7916, 6764, 52222]ax.bar(x, y, width=0.5, color=['b', 'r', 'g', 'y', 'c', 'm', 'y', 'k', 'c', 'g', 'b'])ax.set_xticks(x, movie_name, fontsize=10)plt.show()
运行结果:
4. 饼图
饼图由不同类别数据所占的比例构成,一般用来展示不同类别的数据所占总体的比例。
import numpy as np
import matplotlib.pyplot as plt#中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseif __name__ == '__main__':fig = plt.figure(figsize=(15,8))ax = fig.add_subplot()data = [23, 17, 35, 29, 12]data_label = ['C', 'C++', 'Java', 'Python', 'PHP']ax.pie(data, labels=data_label, autopct='%1.2f%%', colors=['red', 'blue', 'yellow', 'green', 'orange'])plt.show()
运行结果: