Matplotlib
Matplotlib

目录
一、Matplotlib基础
二、两种画图接口
三、线形图
四、散点图
五、等高线图
六、直方图
七、图例配置
八、颜色条配置
九、多子图
十、文字和注释
十一、三维图
一、Matplotlib基础
1.安装Matplotlib
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ matplotlib
2.库导入
import matplotlib as mpl
import matplotlib.pyplot as plt
3.启动Matplotlib
在IPython Notebook和IPython shell中需要使用启动命令
交互方式:%matplotlib notebook
静态方式:%matplotlib inline
4.风格样式设置
plt.style.use('内置风格样式名称')
- 查看可用风格样式
plt.style.available
‘bmh’, ‘classic’, ‘dark_background’, ‘fast’, ‘fivethirtyeight’, ‘ggplot’, ‘grayscale’, ‘seaborn-bright’, ‘seaborn-muted’, ‘seaborn-notebook’, ‘seaborn-paper’, ‘seaborn-pastel’, ‘seaborn-poster’, ‘seaborn-talk’, ‘seaborn-ticks’, ‘seaborn-white’, ‘seaborn-whitegrid’, ‘seaborn’, ‘Solarize_Light2’, ‘tableau-colorblind10’, ‘_classic_test’

5.创建图形和坐标轴
fig = plt.figure()
ax = plt.axes()
6.画图
plt.plot(变量1, 变量2, 风格参数)
plt.show()
7.将图形保存为文件
fig.savefig('文件名.png')
8.加载并显示图片
from IPython.display import Image
Image('文件名.png')
- 获取支持的图像格式
fig.canvas.get_supported_filetypes()
二、两种画图接口
1.MATLAB风格接口
# 创建图形
plt.figure()
plt.subplot(2, 1, 1)
plt.plot(x, np.sin(x))
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x))
这种接口最重要的特征是有状态的(stateful):它会持续跟踪当前的图形和坐标轴进行绘制。
plt.gcf():获取当前图形
plt.gca():获取当前坐标轴
2.面向对象接口
# ax是一个包含两个Axes对象的数组
fig, ax = plt.subplots(2)
# 在每个Axes对象上调用plot方法
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x))
三、线形图
figure(plt.Figure类的一个实例)可以被看作一个能够容纳各种坐标轴、图形、文字和标签的容器。
axes(plt.Axes类的一个实例)是一个带有刻度和标签的矩形。
plt.style.use('seaborn-whitegrid')
fig = plt.figure()
ax = plt.axes()

1.线条颜色
通过设置plt.plot()方法的color参数可以调节线条的颜色。

示例:
# 颜色风格:color参数
plt.plot(x, np.sin(x - 0), color='blue') # 标准颜色名称
plt.plot(x, np.sin(x - 1), color='g') # 缩写颜色代码
plt.plot(x, np.sin(x - 2), color='0.75') # 范围在0-1的灰度值
plt.plot(x, np.sin(x - 3), color='#FFDD44') # 十六进制(RRGGBB,范围在00-FF)
plt.plot(x, np.sin(x - 4), color=(1.0, 0.2, 0.3)) # RGB元组,范围在0-1
plt.plot(x, np.sin(x - 5), color='chartreuser') # HTML颜色名称

2.线条风格

通过设置plt.plot()方法的linestyle参数可以调节线条的风格。
# 线条风格:linestyle参数
plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted')
plt.plot(x, x + 4, linestyle='-') # 实线
plt.plot(x, x + 5, linestyle='--') # 虚线
plt.plot(x, x + 6, linestyle='-.') # 点划线
plt.plot(x, x + 7, linestyle=':') # 实点线

3.坐标轴上下限
(1)plt.xlim()、plt.ylim()
plt.xlim(x轴下限, x轴上限)
plt.ylim(y轴下限, y轴上限)
(2)plt.axis()
plt.axis([轴下限, x轴上限, y轴下限, y轴上限])
plt.axis()其他功能:
- 1.使坐标轴按照图形内容自动缩紧
plt.axis('tight')
- 2.使坐标轴比例为1:1
plt.axis('equal')
4.设置图形标签
(1)设置标题
plt.title('图形标题')
plt.xlabel('x轴标题')
plt.ylabel('y轴标题')
(2)设置图例
使用plt.plot的label参数设置图例信息,调用plt.legend()显示图例。
高级图例设置方法见七、图例设置
# 设置图例
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
# 显示图例
plt.legend()
注意:使用面向对象风格设置时,需要做如下形式的变换:
plt.xlim() => ax.set_xlim()
plt.ylim() => ax.set_ylim()
plt.title() => ax.set_title()
plt.xlabel() => ax.set_xlabel
plt.ylabel() => ax.set_ylabel
四、散点图
1.使用plt.plot()作散点图
plt.plot(变量1, 变量2, '图形标记')

示例:
# 图形标记
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt.plot(rng.rand(5), rng.rand(5), marker, label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8)

其他属性:
# 其他属性
plt.plot(x, y, '-p',
color='gray',
markersize=15,
markerfacecolor='white',
markeredgecolor='pink',
markeredgewidth=2)
plt.ylim(-1.2, 1.2)

2.使用plt.scatter()作散点图
plt.scatter与plt.plot相比,拥有更高的灵活性,可以单独控制每个散点与数据匹配
plt.scatter(x, y, marker='图形标记')
示例:
# 通过scatter可以控制每个点
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis')
# 显示颜色条
plt.colorbar()

3.基本误差线
plt.errorbar(x, y, yerr=None, xerr=None, fmt='')
示例:
# 误差线
x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x, y, yerr=dy, fmt='.k')

五、等高线图
示例用例数据:
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
1.简易等高线图
当只有一种颜色时,实线表示正数,虚线表示负数
plt.contour(X, Y, Z, colors='black')

2.彩色等高线图
使用plt.cm.<Tab>可以查看plt.cm模块的配色方案
# RdGy:红灰方案
plt.contour(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()

3.带填充色等高线图
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()

4.渐变图
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image')

5.带数据标签等高线图
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy', alpha=0.5)
plt.colorbar()

六、直方图
1.一维频次直方图
plt.hist(data)
示例:
data = np.random.randn(1000)
plt.hist(data, bins=30, density=True, alpha=0.5, histtype='stepfilled', color='steelblue',edgecolor='none')

- 在一张画布中作多个直方图
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs)

2.二维频次直方图
plt.hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, data=None, **kwargs)
示例:
mean = [0, 0]
cov = [[1,1], [1,2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')

- 使用六边形区间划分
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='counts in bin')

七、图例配置
1.plt.legend
ax.legend(loc='位置参数')

x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend(loc='upper left', frameon=False)

- 多列图例
leg = ax.legend(loc='lower center', ncol=2)

- 圆角边框
leg = ax.legend(fancybox=True, framealpha=0.5, shadow=True, borderpad=1)

圆角边框在plt.style.use('classic')下生效。
2.多图例(Legend类)
创建多个图例并将图例添加到图上
from matplotlib.legend import Legend
leg = Legend(ax, lines[位置(切片)], ['标签名1', '标签名2', ......], loc='lower right', frameon=False)
ax.add_artist(leg)
示例:
fig, ax = plt.subplots()
styles = ['-', '--', '-.', ':']
x = np.linspace(0, 10, 1000)
lines = []
for i in range(4):
lines += ax.plot(x, np.sin(x - i * np.pi / 2), styles[i], color='black')
ax.axis('equal')
# 设置第一个图例
ax.legend(lines[:2], ['lineA', 'lineB'], loc='upper right', frameon=False)
# 创建第二个图例,通过add_artist方法添加到图上
from matplotlib.legend import Legend
leg = Legend(ax, lines[2:], ['lineC', 'lineD'], loc='lower right', frameon=False)
ax.add_artist(leg)

八、颜色条配置
1.显示颜色条
plt.colorbar()
九、多子图
1.手动创建子图
(1)通过plt.axes()创建子图
位置参数:bottom和left参数是相对于坐标轴原点的位置,占图形的百分数。
尺寸参数:width和height参数是子图的宽度和高度,占图形的百分数。
plt.axes([bottom, left, width, height])
示例:
ax1 = plt.axes()
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

(2)通过fig.add_axes()创建子图
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))

2.网格子图
(1)plt.subplot()方法
循环生成多个子图
for i in range(1, 行数×列数+1):
plt.subplot(行数, 列数, i)
示例:
for i in range(1, 7):
plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center')

- 使用plt.subplots_adjust()方法调整图与图之间的间隔
fig.subplots_adjust(hspace=上下距离(子图百分比), wspace=左右距离(子图百分比))
示例:
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center')

(2)plt.subplots()方法
fig, ax = plt.subplots(行数, 列数, sharex='col', sharey='row')
示例:
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)), fontsize=18, ha='center')

3.复杂排列网格子图
grid = plt.GridSpec(行数, 列数, wspace=左右距离(子图百分比), hspace=上下距离(子图百分比))
plt.subplot(grid[行切片, 列切片])
示例:
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
plt.subplot(grid[0, 0])
plt.subplot(grid[0, 1:])
plt.subplot(grid[1, :2])
plt.subplot(grid[1, 2])

4.综合示例:多轴频次直方图
# 创建正态分布的数据
mean = [0, 0]
cov = [
[1, 1],
[1, 2]
]
x, y = np.random.multivariate_normal(mean, cov, 3000).T
# 设置坐标轴及网格配置方式
fig = plt.figure(figsize=(6, 6))
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
# 主坐标轴画散点图
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
# 次坐标画频率直方图
x_hist.hist(x, 40, histtype='stepfilled', orientation='vertical', color='gray')
x_hist.invert_yaxis()
y_hist.hist(y, 40, histtype='stepfilled', orientation='horizontal', color='gray')
y_hist.invert_xaxis()

十、文字和注释
1.箭头与注释
ax.annotate('箭头注释文本', xy=(箭头尖位置), xytext=(箭头注释文本位置), arrowprops=dict(参数字典))
arrowprops参数
①普通箭头(不包含arrowstyle参数)

②风格箭头(包含arrowstyle参数)

示例:
fig, ax = plt.subplots()
x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')
ax.annotate('local maximum', xy=(6.28, 1), xytext=(10, 4), arrowprops=dict(facecolor='black', shrink=0.05))
ax.annotate('local minimum', xy=(5*np.pi, -1), xytext=(2, -6), arrowprops=dict(arrowstyle='->', connectionstyle='angle3, angleA=0, angleB=-90'))

十一、三维图
1.导入包
from mpl_toolkits import mplot3d
2.创建图形和坐标轴
fig = plt.figure()
ax = plt.axes(projection='3d')

3.画图
ax = plt.axes(projection='3d')
ax.plot3D(xline, yline, zline, '颜色')
ax.scatter3D(xdata, ydata, zdata, c=颜色渐变参照值, cmap='颜色')
示例:
ax = plt.axes(projection='3d')
# 三维线的数据
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
# 绘制三维线
ax.plot3D(xline, yline, zline, 'gray')
# 三维散点的数据
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
# 绘制三维散点
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens')

4.等高线图
ax.contour3D(X, Y, Z, 层数, cmap='颜色')
示例:
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='Blues')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

- 调整初始观测角度
ax.view_init(垂直角度, 水平角度)
5.线框图
ax.plot_wireframe(X, Y, Z, color='颜色')
示例:
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe')

6.曲面图
ax.plot_surface(X, Y, Z, rstride=水平下采样步长, cstride=竖直下采样步长, cmap='viridis', edgecolor='none')
示例:
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('surface')

