fig, axs = plt.subplots(2, 2, figsize=(12, 4))
时间: 2023-09-23 19:04:05 浏览: 59
这段代码创建了一个大小为 12x4 的画布,并将画布分成 2 行 2 列的四个子图区域。`axs` 是一个包含四个子图对象的二维数组,可以分别在每个子图中绘制不同的图形。
下面是一个例子,展示如何在这四个子图中绘制不同的图形:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x)
# 创建画布和子图
fig, axs = plt.subplots(2, 2, figsize=(12, 4))
# 在子图中绘制图形
axs[0, 0].plot(x, y1)
axs[0, 0].set_title('sin(x)')
axs[0, 1].plot(x, y2)
axs[0, 1].set_title('cos(x)')
axs[1, 0].plot(x, y3)
axs[1, 0].set_title('tan(x)')
axs[1, 1].plot(x, y4)
axs[1, 1].set_title('exp(x)')
# 显示图形
plt.show()
```
运行以上代码,会在同一画布上绘制四个不同的图形:正弦曲线、余弦曲线、正切曲线和指数曲线。注意,在二维数组中使用 `axs[row, col]` 的方式访问每个子图对象。
相关问题
fig, axs = plt.subplots(r,shared=‘all’)
`fig, axs = plt.subplots(r, shared='all')` 是一个 Matplotlib 绘制多个子图时比较方便的方式,它可以创建一个 `r` 行、`r` 列的子图网格,并将它们存储在一个名为 `axs` 的二维 numpy 数组中。
`shared='all'` 参数表示所有子图共享相同的 x 轴和 y 轴刻度。这意味着,如果某个子图的数据范围改变了,所有其他子图的刻度也会相应地调整。
以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axs = plt.subplots(2, 2, figsize=(8, 6), sharex='all', sharey='all')
axs[0, 0].plot(x, y1)
axs[0, 1].plot(x, y2)
axs[1, 0].plot(x, y1+y2)
axs[1, 1].plot(x, y1*y2)
plt.show()
```
在这里,`fig, axs = plt.subplots(2, 2, figsize=(8, 6), sharex='all', sharey='all')` 创建了一个 2x2 的子图网格,每个子图都共享相同的 x 轴和 y 轴刻度。然后,我们在四个子图中绘制了不同的函数。注意,`axs` 是一个 2x2 的 numpy 数组,可以用来对每个子图进行进一步的定制。
fig,ax = plt.subplots()什么意思
这行代码是用来创建一个包含一个或多个子图(subplot)的图形窗口(figure)。
`fig, ax = plt.subplots()` 中,`fig` 是图形窗口对象,而 `ax` 是子图对象。在 Matplotlib 中,图形窗口可以包含一个或多个子图。通常情况下,我们只需要一个子图(也就是一个坐标系),所以可以把 `ax` 看作是一个坐标系对象。
如果没有指定参数,`plt.subplots()` 默认会创建一个包含一个子图的图形窗口。如果要创建包含多个子图的图形窗口,可以通过指定 `nrows` 和 `ncols` 参数来实现,例如 `fig, axs = plt.subplots(nrows=2, ncols=3)` 就可以创建一个包含 2 行 3 列共 6 个子图的图形窗口,其中 `axs` 是一个包含 6 个子图对象的数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)