首页 > 解决方案 > Matplolib subplots fig 和 axs 变量的用途是什么

问题描述

考虑以下代码:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
data = np.random.randn(2, 100)

fig, axs = plt.subplots(2, 2, figsize=(5, 5))
axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])

plt.show()

我知道为了创建子图,您需要编写以下行:

fig, axs = plt.subplots(2, 2, figsize=(5, 5)

但是我的问题是关于这条线的含义,因为它通过产生变量 fig 和 axs 实际实现了什么,以及为什么稍后我们使用 ax[0,0] 而不是 fig[0,0]

标签: matplotlibhistogramsubplotfig

解决方案


fig描述了整个图形,但axs在这种情况下,指的是图形中的所有子图。由于您定义了 2 行和 2 列子图,因此您将每个子图称为axs[0,0]左上角子图和axs[1,1]右下角子图。为了更改子图的大小,您必须更改嵌入子图的整体图形的大小。

差异是微妙的,但可以在图中找到多个子图或仅一个子图。因此,要绘制一条线,您可以在子图轴上而不是在图形上执行此操作。


推荐阅读