📜  如何使用Python在 Matplotlib 中创建子图?

📅  最后修改于: 2022-05-13 01:54:32.534000             🧑  作者: Mango

如何使用Python在 Matplotlib 中创建子图?

先决条件: Matplotlib  

在本文中,我们将学习如何使用 Matplotlib 和Python为图形添加标记。为此,必须熟悉以下概念:

  • Matplotlib Matplotlib 是一个巨大的Python可视化库,用于数组的二维绘图。 Matplotlib 可能是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起计算。它是由 John Hunter 在 2002 年引入的。
  • Subplots : matplotlib.pyplot.subplots() 方法提供了一种在单个图形上绘制多个图的方法。给定行数和列数,它返回一个元组 (fig, ax),给出一个带有 ax 轴数组的单个图形 fig。

方法

  • 导入包
  • 导入或创建一些数据
  • 创建子图对象。
  • 用它画一个图。

示例 1:

Python3
# importing packages
import matplotlib.pyplot as plt
import numpy as np
  
# making subplots objects
fig, ax = plt.subplots(3, 3)
  
# draw graph
for i in ax:
    for j in i:
        j.plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
  
plt.show()


Python3
# importing packages
import matplotlib.pyplot as plt
import numpy as np
  
# making subplots objects
fig, ax = plt.subplots(2, 2)
  
# draw graph
ax[0][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[0][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[1][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[1][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
  
plt.show()


Python3
# importing packages
import matplotlib.pyplot as plt
import numpy as np
  
# making subplots objects
fig, ax = plt.subplots(2, 2)
  
# create data
x = np.linspace(0, 10, 1000)
  
# draw graph
ax[0, 0].plot(x, np.sin(x), 'r-.')
ax[0, 1].plot(x, np.cos(x), 'g--')
ax[1, 0].plot(x, np.tan(x), 'y-')
ax[1, 1].plot(x, np.sinc(x), 'c.-')
  
plt.show()


输出 :

示例 2:

蟒蛇3

# importing packages
import matplotlib.pyplot as plt
import numpy as np
  
# making subplots objects
fig, ax = plt.subplots(2, 2)
  
# draw graph
ax[0][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[0][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[1][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
ax[1][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
  
plt.show()

输出 :

示例 3:

蟒蛇3

# importing packages
import matplotlib.pyplot as plt
import numpy as np
  
# making subplots objects
fig, ax = plt.subplots(2, 2)
  
# create data
x = np.linspace(0, 10, 1000)
  
# draw graph
ax[0, 0].plot(x, np.sin(x), 'r-.')
ax[0, 1].plot(x, np.cos(x), 'g--')
ax[1, 0].plot(x, np.tan(x), 'y-')
ax[1, 1].plot(x, np.sinc(x), 'c.-')
  
plt.show()

输出 :