Matplotlib 子图 – 使用 Matplotlib 绘制多个图形

在本文中,我们将学习如何创建 Matplotlib 子图。

在实践中,我们经常需要多个图来可视化变量,这时就需要使用子图了。Matplotlib子图方法是一种方便的函数,用于在单个图中创建多个图。

使用 Matplotlib 创建基本绘图

在 Matplotlib 中创建绘图是一项简单的任务,可以通过一行代码和一些输入参数来实现。下面的代码展示了如何使用单个图形进行简单的绘图。

#Importing required libraries
import matplotlib.pyplot as plt
import numpy as np
 
#Create data
data = np.arange(1,5,1)
 
#Plotting the data:
plt.plot(data)
简单绘图

plt.plot()显示输入数据的线图。

创建 Matplotlib 子图

现在考虑一种情况,我们需要多个图来解释我们的数据。例如,我们有一个以温度和降雨率作为变量的数据集,我们需要可视化数据。

想到的一件事是将两个变量绘制在一个图中,但温度(开尔文)的测量尺度与降雨率(毫米)的测量尺度不同。

这里我们需要为两者绘制一个单独的图,以便进行视觉解释。Matplotlib 子图是我们制作多个绘图所需的,我们将详细探讨它。

1.使用subplots()方法

让我们对使用matplotlib.subplots.

matplotlib subplots() 方法需要多个行和多个列作为其输入参数,并返回一个图形对象和轴对象。

每个轴对象都可以使用简单的索引来访问。选择所需的绘图轴后,绘图过程将按照正常过程进行,就像我们在上面的代码中所做的那样。

让我们创建 4 个像网格一样排列的子图。

#Importing required libraries
import matplotlib.pyplot as plt
 
# Creates fig and ax from subplots().
fig , ax = plt.subplots(nrows = 2, ncols = 2)
4 个次要情节

2. 访问子图

访问各个轴非常简单。让我们对第一个和最后一个子图进行一些绘图。

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
 
#Loading Dataset
data = load_iris()
df = data.data
 
fig , ax = plt.subplots(nrows = 2, ncols = 2, figsize=(8,6))
 
#Plotting on the 1st axes
ax[0][0].scatter(df[:,0],df[:,1] , color = 'black')
 
#Plotting on the last axes
ax[1][1].scatter(df[:,1],df[:,2] , color = 'red')
访问第一个和第四个子图

将每个轴视为排列在 2D 数组中的一些对象,访问每个子图类似于访问 2D 数组中的元素。

  • ax[0][0]表示我们首先选择第一行(索引 0)和该行中的第一个元素(索引 0)。
  • ax[1][1]表示我们首先选择第二行(索引 1)和该行中的第二个元素(索引 1)。

3.具有共享轴的Matplotlib子图

在许多应用中,我们需要子图的轴彼此对齐。matplotlib subplots() 方法接受另外两个参数,即sharex和 ,sharey以便所有子图轴具有相似的比例。

#Import required libraries
import matplotlib.pyplot as plt
 
#Plotting
fig, ax = plt.subplots(2, 3, sharex=True, sharey=True)
for i in range(0,2):
    for j in range(0,3):
        ax[i][j].text(0.5, 0.5, str((i,j)),fontsize=18, ha='center')
具有共享轴的子图

4.使用add_subplot()方法

add_subplot是 Matplotlibfigure对象的一个​​属性。每当我们希望将子图一一添加到图形中时,就会使用它。

让我们用示例代码来演示这一点。

#Importing libraries
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
 
#Loading Data to plot
data = load_iris()
df = data.data
 
#Create a figure object
fig = plt.figure(figsize=(8,8))
 
#Adding one subplot to the figure
ax_1 = fig.add_subplot(2, 2, 1) #selecting 1st out of 4 subplots
ax_1.scatter(df[:,0],df[:,1] , color = 'black')
 
#Adding one more subplot
ax_2 = fig.add_subplot(2,2,4)
ax_2.scatter(df[:,0],df[:,1] , color = 'red')
一一添加子图

在上面的代码中,add_subplot图形对象的属性需要许多行和列作为输入参数以及子图的索引。

但在这里,我们不需要将子图索引为二维数组,而是只需要传递一个类似于图形编号的整数。

fig.add_subplot(2, 2, 1)上面的代码将首先创建一个 2×2 子图网格,并返回第一个子图轴对象,我们可以在其上绘制数据。

结论

在本文中,我们了解了如何在单个图中可视化多个图中的数据、subplots方法的使用以及创建子图的多种方式。

快乐学习!