使用pip安装matplotlib:
pip install matplotlib
导入模块并起别名plt:
import matplotlib.pyplot as plt
使用 figure() 函数创建画布
plt.figure(name) # 传入字符串可为画布命名
使用 subplot() 函数在画布创建子图
plt.subplot(2, 1, 1) # 创建2*1的子图,当前是第1个子图
#绘图1
plt.subplot(2, 1, 2) # 当前在第2个子图,前两个参数和创建时一样
#绘图2
使用 plot() 函数画函数图像
plt.plot(x, y) # x是一定范围内离散的数(点),y是x的函数值
plt.plot(x, y1, x, y2) # 在同一坐标轴绘制多个函数图像
样式:
plt.style.use() # 传入'classic'引用经典样式,也可以引用其他样式
plt.plot(x, y, '--') # 虚线
plt.plot(x, y, 'o') # 点状
plt.plot(x, y, '-p', markersize=10, linewidth=1) # 五边形,形状大小,线的粗细
plt.plot(x, y, color='red') # 颜色
plt.plot(x, y, label='sin(x)') # 标签
plt.legend(loc=0) # 显示标签, loc控制位置,0与'best'等价:最佳位置,1与'upper right'等价:右上角,2与'upper left'等价:左上角,3与'lower left'等价:左下角,4与'lower right'等价:右下角
函数图像实例:
import matplotlib.pyplot as plt
import numpy as np
# 横轴取值范围-Π到Π,等间隔取100个点
x = np.linspace(-np.pi, np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure() # 创建画布
plt.subplot(3, 1, 1) #创建3*1子图,当前在第1个子图
plt.plot(x, y1, '--', label='sin(x)') # 使用plot()函数画y1函数图像
plt.legend() # 显示标签
plt.subplot(3, 1, 2) #当前在第2个子图
plt.plot(x, y2, 'o', color='yellow', label='cos(x)') # 使用plot()函数画y2函数图像
plt.legend() # 显示标签
plt.subplot(3, 1, 3) #当前在第3个子图
plt.plot(x, y1, x, y2, label='sin(x)', label='cos(x)') # 使用plot()函数画y1和y2函数图像
plt.legend() # 显示标签
# 使用show()函数弹窗显示图形
plt.show()
散点图
plt.scatter(x, y)
散点图实例:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic') # 引用经典样式
x = np.random.random(100) # 生成100个[0, 1)随机数
y = np.random.random(100)
colors = np.random.random(100)
size = 1000*np.random.random(100)
plt.scatter(x, y, c=colors, s=size, alpha=0.5) # 绘制散点图
plt.colorbar() # 显示颜色条
plt.show()