可以将Figure对象分为多个区域,每个区域分别放置一个Axes对象进行绘图。
subplot命令
subplot命令可以用来直接指定具体的子图位置。
matplotlib.pyplot.subplot(
nrows / ncols = 1 : 图组的行/列数。
整个Figure对象区域被划分为nrows行 * ncols列。
然后按照从左到右、从上到下的顺序对每个区域进行编号,左上区域的编号为1。
index : 指定所创建Axes对象所在的区域。
)
如果numRows、numCols和Index三个参数都小于10,则可以把它们缩写成一个整数。
subplot(323)和subplot(3,2,3)的含义相同。
如果新创建的子图和之前创建的子图区域有重叠的部分,则之前的子图将被删除。
plt.subplot(221)
plt.subplot(222)
plt.subplot(212)
plt.plot([1,2,2,1])
plt.show()
切换使用的子图对象
matplotlib.pyplot.sca(ax) : Set the current Axes instance to ax
子图对象所在的图表对象也会被自动设定为当前图表对象。
plt.subplot(221)
ax1 = plt.subplot(222)
plt.subplot(212)
plt.sca(ax1)
plt.plot([1,2,2,1])
plt.show()
subplots命令
subplot命令需要分别指定每个子图,如果希望批量快速生成子图的网格框架,则可以使用subplots命令。
matplotlib.pyplot.subplots(
nrows /ncols = 1 : 图形网格的行/列数
sharex, sharey = False : 在图组中是否共用行/列坐标轴
True or ‘all’: 对应的单元格都将共用行/列坐标轴
False or ‘none’: 各单元格独立设定行/列坐标轴
‘row’: 同一行的单元格将共用行/列坐标轴
‘col’: 同一列的单元格将共用行/列坐标轴
squeeze = True : 是否尽量简化返回的Axes对象
False时即使只有一个单元格,也返回二维数组
subplot_kw : dict, 未来调用add_subplot()建立子图时需要传送的参数
) 返回值:
fig : matplotlib.figure.Figure对象
ax : Axes对象/Axes数组对象
fig, axes = plt.subplots(2, 3)
fig, ax0 = plt.subplots()
sns.distplot(ccss.index1, ax = ax0)
ax0.set_title('Sample plot')
f, (ax1, ax2) = plt.subplots(1, 2, sharey = True)
ax1.hist(ccss.index1)
ax1.set_title('Sharing Y axis')
ax2.plot([0,200,300])
f, (ax1, ax2) = plt.subplots(1, 2)
sns.boxplot(y = ccss.index1, ax = ax1)
ax1.set_title('总信心指数')
sns.boxplot(y = ccss.s3, ax = ax2)
ax2.set_title('年龄')
fig, axes = plt.subplots(2, 2)
sns.boxplot(y = ccss.index1, ax = axes[0, 0])
sns.boxplot(y = ccss.s3, ax = axes[1, 1])
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1)
plt.figure(2)
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
x = np.linspace(0, 3, 100)
for i in range(5):
plt.figure(1)
plt.plot(x, np.exp(i*x/3))
plt.sca(ax1)
plt.plot(x, np.sin(i*x))
plt.sca(ax2)
plt.plot(x, np.cos(i*x))
plt.show()
Original: https://blog.csdn.net/weixin_47700141/article/details/120090671
Author: juicy-hua
Title: 8-2 分区绘制多个子图
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/769718/
转载文章受原作者版权保护。转载请注明原作者出处!