matplotlib —— subplot子图

本文详细介绍了在matplotlib中如何创建和使用subplot,包括通过`add_subplot()`和`plt.subplot()`两种方法创建子图,以及在指定的subplot上进行绘图和设置属性的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建subplot

1、使用add_subplot( )创建
In [121]: fig=plt.figure()

In [122]: ax1=fig.add_subplot(2,2,1)

In [123]: ax2=fig.add_subplot(2,2,2)

In [124]: ax3=fig.add_subplot(2,2,3)

In [125]: fig.show()

2、使用plt.subplot( )创建

创建一个新的Figure,并返回一个含有已创建的subplot对象的Numpy数组

In [184]: fig1,axes=plt.subplots(2,2)

In [185]: axes[0,0].scatter(x,y)
Out[185]: <matplotlib.collections.PathCollection at 0x140237b8>

In [186]: axes[1,1].plot(x,y)
Out[186]: [<matplotlib.lines.Line2D at 0x1423ed30>]

In [187]: fig1.show()


pyplot.subplots的选项

参数说明
nrowssubplot的行数
ncolssubplot的列数
sharex所有的subplot应该使用相同的X轴刻度
sharey所有的subplot应该使用相同的Y轴刻度
subplot_kw用于创建各subplot的关键字字典

在指定的subplot上绘图

In [144]: ax1.plot(np.random.randn(50).cumsum())
Out[144]: [<matplotlib.lines.Line2D at 0x9d57208>]

In [145]: fig.show()


在指定的subplot上绘制图形

In [166]: rect=plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.3)

In [167]: circ=plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)

In [168]: ax2.add_patch(rect)
Out[168]: <matplotlib.patches.Rectangle at 0x14732048>

In [169]: ax2.add_patch(circ)
Out[169]: <matplotlib.patches.Circle at 0x1472ef98>

In [170]: fig.show()


设置指定的subplot的属性

In [199]: ax2.set_xlabel('x-label')
Out[199]: <matplotlib.text.Text at 0x9b14668>

In [200]: ax2.set_ylabel('y-label')
Out[200]: <matplotlib.text.Text at 0x9c55978>

In [201]: ax2.set_title('Show Shapes')
Out[201]: <matplotlib.text.Text at 0x9c852e8>

In [202]: fig.show()

### 创建嵌套Matplotlib 中,可以利用面向对象接口创建复杂的多层级嵌套。这涉及到先建立一个主要的形对象,再在此基础上添加不同级别的 `axes` 实体[^1]。 对于构建具有多层次结构的像而言,一种常见的方式是采用 GridSpec 来更精细地控制各个轴的位置和大小比例。GridSpec 可以被看作是一个容器,里面放置着一个个的小格——这些就是实际用来绘制表的地方。下面给出一段 Python 代码作为示范: ```python import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec # 创建一个新的 figure 对象 fig = plt.figure(figsize=(8, 6)) # 定义外层网格布局 (2 行 1 列) outer_grid = GridSpec(2, 1, height_ratios=[1, 3], hspace=0.5) # 在第一个位置上添加一个简单的 subplot ax1 = fig.add_subplot(outer_grid[0]) ax1.set_title('Top Level Plot') ax1.plot([0, 1, 2], [0, 1, 0]) # 定义内层网格布局,在第二个大单元格内部划分成两列 inner_grid = GridSpecFromSubplotSpec(1, 2, subplot_spec=outer_grid[1], wspace=0.4) # 向内层的第一个小单元格中加入新的 subplot ax2 = fig.add_subplot(inner_grid[0]) ax2.set_title('Nested Left Subplot') ax2.scatter([0.3, 0.7], [0.3, 0.7]) # 向内层的第二个小单元格中也加入新的 subplot ax3 = fig.add_subplot(inner_grid[1]) ax3.set_title('Nested Right Subplot') ax3.bar(['A', 'B'], [5, 7]) plt.show() ``` 这段脚本展示了怎样在一个较大的窗口里安排两个水平排列的小窗口,并且在外围还有一个独立的大窗口。这里的关键在于使用了 `GridSpec` 和它的变种 `GridSpecFromSubplotSpec` 来精确指定各部分之间的相对尺寸以及它们之间留白的空间量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值