# 使用 Matplotlib 创建多个子图

Salman Mehmood 2024年2月15日

## 使用 Matplotlib 中的 `subplots()` 方法创建绘图

``````import matplotlib.pyplot as plt
``````

``````plt.style.use("seaborn")
``````

`subplots()` 方法有助于在单个窗口或图形中创建多个绘图，并且此方法返回两个内容。第一个是图形，第二个是轴，用于在不同轴上创建子图。

``````fig, axes = plt.subplots(figsize=(6, 4))
``````

``````x1 = [0, 4, 8, 12, 16, 20, 24]
y1 = [8, 1, 10, 5, 12, 16, 7]
``````

``````import matplotlib.pyplot as plt

# use stylish plot from seaborn
plt.style.use("seaborn")

# create single plot in a figure
fig, axes = plt.subplots(figsize=(6, 4))

x1 = [0, 4, 8, 12, 16, 20, 24]
y1 = [8, 1, 10, 5, 12, 16, 7]
# Creates a line plot
axes.plot(x1, y1)
# set the title of appeared window
axes.set_title("A single Line-plot")

plt.show()
``````

## 使用 Matplotlib 在一个方向上创建两个子图

``````fig, axes = plt.subplots(2, figsize=(6, 4))
``````

`subplots()` 方法的前两个参数是可选的。在上面的代码中，我们在一行中创建了两个图。

``````axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
``````

``````import matplotlib.pyplot as plt

# use stylish plot from seaborn
plt.style.use("seaborn")

# create single plot in a figure
fig, axes = plt.subplots(2, figsize=(6, 4))

x1 = [0, 4, 8, 12, 16, 20, 24]
y1 = [8, 1, 10, 5, 12, 16, 7]

# second dataset

x2 = [0, 5, 10, 15, 20, 25, 30]
y2 = [2, 8, 1, 15, 3, 20, 25]

# Creates a line plot
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)

# displays a super title on top of the figure
fig.suptitle("This is a vertical plot in single direction")
plt.show()
``````

## 在 Matplotlib 中的一个图中创建多个子图

``````axes[0][0].bar(x1, y1)
``````

``````import matplotlib.pyplot as plt

# use stylish plot from seaborn
plt.style.use("seaborn")

# create single plot in a figure
fig, axes = plt.subplots(2, 2, figsize=(6, 4), constrained_layout=True)

x1 = [0, 4, 8, 12, 16, 20, 24]
y1 = [8, 1, 10, 5, 12, 16, 7]

# second dataset

x2 = [0, 5, 10, 15, 20, 25, 30]
y2 = [2, 8, 1, 15, 3, 20, 25]

# set the title of appeared window
axes[0][0].set_title("Bar-plot axis 0,0")
axes[0][1].set_title("Scatter-plot axis 0,1")
axes[1][0].set_title("Line-plot axis 1,0")
axes[1][1].set_title("Two Line-plots axis 1,1")

# Creates a line plot
axes[0][0].bar(x1, y1)
axes[0][0].bar(x2, y2)
axes[0][1].scatter(x1, y1)
axes[1][0].plot(x1, y1)
axes[1][1].plot(x1, y1)
axes[1][1].plot(x2, y2, color="red")

# displays a super title on top of the figure
fig.suptitle("Different Subplots With two Directions")
plt.show()
``````

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.