使用subplot2grid(函数绘制三个子图(要求:子图 分布均匀,大小适中,使用“紧密布局”谓整间距,
时间: 2024-02-23 17:58:15 浏览: 17
好的,下面是使用subplot2grid函数绘制三个子图的代码:
```python
import matplotlib.pyplot as plt
# 准备数据
x = [1, 2, 3, 4, 5, 6]
y1 = [10, 8, 6, 7, 9, 12]
y2 = [5, 7, 8, 9, 6, 4]
y3 = [3, 5, 6, 4, 8, 9]
# 创建画布,并使用subplot2grid函数定义子图
fig = plt.figure(figsize=(10, 6))
ax1 = plt.subplot2grid((2, 2), (0, 0))
ax2 = plt.subplot2grid((2, 2), (0, 1))
ax3 = plt.subplot2grid((2, 2), (1, 0), colspan=2)
# 在子图中绘制数据
ax1.plot(x, y1)
ax1.set_title('Subplot 1')
ax2.plot(x, y2)
ax2.set_title('Subplot 2')
ax3.plot(x, y3)
ax3.set_title('Subplot 3')
# 调整子图之间的间距
plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.3, hspace=0.3)
# 显示图形
plt.show()
```
代码中,使用了subplot2grid函数来定义三个子图的位置和大小。其中,(2, 2)表示整个画布被分成了2行2列,(0, 0)、(0, 1)和(1, 0)表示三个子图的位置,colspan=2表示第三个子图占据了两个列。
在子图中,使用plot函数分别绘制了三组数据,并使用set_title函数设置了每个子图的标题。最后,使用subplots_adjust函数调整子图之间的间距,使其更加紧密。最后,使用show函数显示图形。
希望这个代码能够帮助到您!