Python中的 Matplotlib.pyplot.subplot()函数
先决条件: matplotlib
subplot()函数将子图添加到指定网格位置的当前图形。它类似于 subplots()函数,但与 subplots() 不同的是,它一次添加一个子图。因此,要创建多个绘图,您需要使用 subplot()函数编写多行代码。 subplot函数的另一个缺点是它会删除图形上预先存在的图。请参阅示例 1。
它是 Figure.add_subplot 的包装器。
句法:
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(ax)
Parameters :
- args: Either a 3-digit integer or three separate integers describing the position of the subplot.
- pos is a three-digit integer where the first, second, and third integer are nrows,ncols, index.
- projection : [{None, ’aitoff’, ’hammer’, ’lambert’, ’mollweide’, ’polar’, ’rectilinear’, str}, optional]. The projection-type of the subplot (Axes). The default None results in a ’rectilinear’ projection.
- label : [str] A label for the returned axes.
- **kwargs: This method also takes the keyword arguments for the returned axes base class;
except for the figure argument, for e.g facecolor.
Returns : An axes.SubplotBase subclass of Axes or a subclass of Axes. The returned axes base class depends on the projection used.
该函数的实现如下:
示例 1: subplot() 将删除预先存在的绘图。
Python3
# importing hte module
import matplotlib.pyplot as plt
# Data to display on plot
x = [1, 2, 3, 4, 5]
y = [1, 2, 1, 2, 1]
# plot() will create new figure and will add axes object (plot) of above data
plt.plot(x, y, marker="x", color="green")
# subplot() will add plot to current figure deleting existing plot
plt.subplot(121)
Python3
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
z = [1, 3, 1]
# Creating figure object
plt.figure()
# addind first subplot
plt.subplot(121)
plt.plot(x, y, color="orange", marker="*")
# addding second subplot
plt.subplot(122)
plt.plot(z, y, color="yellow", marker="*")
输出:我们可以看到第一个图被 subplot()函数放在一边。
如果你想看到第一个情节注释掉 plt.subplot() 行,你会看到下面的情节
示例 2:
蟒蛇3
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
z = [1, 3, 1]
# Creating figure object
plt.figure()
# addind first subplot
plt.subplot(121)
plt.plot(x, y, color="orange", marker="*")
# addding second subplot
plt.subplot(122)
plt.plot(z, y, color="yellow", marker="*")
输出 :