绘制子图

面向过程的方式绘图

如何绘制如下的图呢?

  • 上半部分:看做2行2列,第1行第1列、第1行第2列分别放一张图
  • 下半部分:看做2行1列,第2行的1列放一张图
  • 通过plt.subplot()绘制子图
    plt.subplot(2,1,1) 形成2行2列的布局,画在第1个位置;
    plt.subplot(211) 两种写法效果完全相同。

在这里插入图片描述

# 绘制子图
import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(0.0,5.0) # 从0.0到5.0,选取50个数字(默认)
x2 = np.linspace(0.0,2.0)
x3 = np.linspace(0.0,10.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) # y1 = cos(2*PI*x1)*e^-x1
y2 = np.cos(2 * np.pi * x2) # y2 = cos(2*PI*x2)
y3 = x3*x3 + 2 # y3 = x3^2 + 2

plt.subplot(2, 2, 1)   # 2行2列,画在第1个位置;
# plt.subplot(221) 效果完全一样
plt.plot(x1, y1, 'o-') # 绘制效果由 圈 和 线 组成
plt.title('A title of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 2, 2)   # 2行2列,画在第2个位置
plt.plot(x2, y2, '.-') # 绘制效果由 点 和 线组成
plt.xlabel('time(s)')
plt.ylabel('Undamped')

plt.subplot(2, 1, 2)   # 2行1列,画在第2个位置
plt.plot(x3, x3, '^-') # 绘制效果
plt.xlabel('x3data')   # x轴标签
plt.ylabel('y3data')   # y轴标签
plt.show()

面向对象的方式绘图

  • 看做2行2列,总共四张图,分别放在对应位置

在这里插入图片描述

# 面向对象方式绘制子图
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
data = np.random.randn(2, 100)

fig, axs = plt.subplots(2, 2, figsize=(5, 5)) # 绘制2行2列
axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])

fig.subplots_adjust(hspace=0.8) # 子图的垂直间隔

plt.show()

绘制多个子图

  • 通过plt.figure()指定某张图
  • 通过plt.subplot()在指定的图上绘制子图
    在这里插入图片描述
# 绘制多个子图
import matplotlib.pyplot as plt

plt.figure(1)     # 第一张图
plt.subplot(211)  # 第一张图中的第一张子图
plt.plot([1,2,3])
plt.subplot(212)  # 第一张图中的第二章子图
plt.plot([4,5,6])

plt.figure(2)     # 第二张图
plt.plot([4,5,6]) # 默认创建子图subplot(111)

plt.figure(1)     # 切换到figure1;子图subplot(212)仍然是当前图
plt.subplot(211)  # 令子图subplot(211)成为figure1的当前图
plt.title('Easy as 1,2,3')
plt.show()
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐