matplotlib之pyplot模块——在特定网格位置中添加一个子图(subplot2grid)

当前有效matplotlib版本为:3.4.1

函数概述

subplot2grid函数的功能是在特定网格位置中添加一个子图。

函数的定义签名为:matplotlib.pyplot.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)

函数的调用签名为:
ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)

函数的参数为:

  • shape:定义子图网格的行数和列数。整数二元组,(nrows, ncols)
  • loc:定义新增子图在子图网格中的位置(行、列索引)。整数二元组,(nrow, ncol)
  • rowspan:定义新增子图向下跨越的行数。可选参数。整数,默认值为1
  • colspan:定义新增子图向右跨越的列数。可选参数。整数,默认值为1
  • fig:用于设置添加子图的Figure对象。可选参数。Figure对象。默认值为当前Figure对象。
  • subplot_kw :用于向创建子图时的底层函数 ~matplotlib.figure.Figure.add_subplot传递关键字参数。可选参数。字典。
  • **kwargs:用于向~.Figure.add_subplot传递的关键字参数。可选参数。

函数的返回值为:
.axes.SubplotBase实例,或其他~.axes.Axes的子类实例。

函数原理

subplot2grid函数其实是fig.add_subplot方法的封装。源码为:

def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):

    if fig is None:
        fig = gcf()

    rows, cols = shape
    gs = GridSpec._check_gridspec_exists(fig, rows, cols)

    subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan)
    ax = fig.add_subplot(subplotspec, **kwargs)
    bbox = ax.bbox
    axes_to_delete = []
    for other_ax in fig.axes:
        if other_ax == ax:
            continue
        if bbox.fully_overlaps(other_ax.bbox):
            axes_to_delete.append(other_ax)
    for ax_to_del in axes_to_delete:
        delaxes(ax_to_del)

    return ax

因此ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)相当于

fig = gcf()
gs = fig.add_gridspec(nrows, ncols)
ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])

案例:简易应用

import matplotlib.pyplot as plt


def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)


fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

annotate_axes(fig)

plt.show()

在这里插入图片描述

案例:混合应用subplotsubplotssubplot2grid函数

import matplotlib.pyplot as plt

# 添加3行3列子图9个子图
fig, axes = plt.subplots(3, 3)
# 为第1个子图绘制图形
axes[0, 0].bar(range(1, 4), range(1, 4))
# 使用subplot函数为第5个子图绘制图形
plt.subplot(335)
plt.plot(1,'o')
# 使用subplot2grid函数将第三行子图合并为1个
plt.subplot2grid((3,3),(2,0),colspan=3)
# 返回值为Axes对象列表,元素个数为7
print(fig.axes)
plt.show()

在这里插入图片描述

subplotsubplot2grid函数之间的比较

subplot函数和subplot2grid函数极其相似。

  • 都可以向当前图像中添加一个子图。
  • 返回值也都是一个Axes实例。
  • 都可以指定子图在子图网格中的位置。

不同之处在于指定子图网格中位置的方法,特别是不规则子图布局时。

  • subplot函数指定位置的方法相对比较隐晦,比如子图位置重叠时,隐含删除被覆盖子图。
  • subplot2grid函数借助gridspec指定位置时相对清晰。

例如:

import matplotlib.pyplot as plt

# 绘制1行2列子图中的第1个子图
plt.subplot(121,facecolor='r')
# 绘制2行2列子图中的第2个子图
plt.subplot(222,facecolor='g')
# 绘制2行2列子图中的第4个子图
plt.subplot(224,facecolor='b')

plt.show()

等价于

import matplotlib.pyplot as plt

# 绘制1行2列子图中的第1个子图
plt.subplot2grid((2,2),(0,0),rowspan=2,facecolor='r')
# 绘制2行2列子图中的第2个子图
plt.subplot(222,facecolor='g')
# 绘制2行2列子图中的第4个子图
plt.subplot(224,facecolor='b')

plt.show()
### Matplotlib Pyplot 功能概述 Matplotlib 是 Python 中广泛使用的绘库,而 `pyplot` 模块提供了类似于 MATLAB 的绘接口。通过该模块可以轻松创建各种类型的表。 为了使用 `pyplot` 进行绘操作,需要先导入相应的库: ```python import matplotlib.pyplot as plt ``` #### 创建简单形 最基础的方式是直接调用 `plt.plot()` 函数来绘制线条或标记点组成的像[^2]。 ```python # 绘制一条简单的折线 plt.plot([1, 2, 3], [4, 5, 6]) plt.show() ``` #### 自定义形属性 可以通过传递额外的关键字参数来自定义所生成的形样式,比如颜色、宽度以及标签等信息[^1]。 ```python # 设置线条的颜色为红色,宽度为2,并添加标题和轴名 plt.plot([0, 1, 2, 3], color="red", linewidth=2.0) plt.title('Simple Line Plot') plt.xlabel('X Axis Label') plt.ylabel('Y Axis Label') plt.grid(True) # 显示网格线 plt.show() ``` #### 复杂形构建 对于更复杂的可视化需求,则推荐采用面向对象 (OO) 方式的编程风格。这种方式允许更加灵活地控制各个组件的行为并支持多布局管理等功能[^3]。 ```python fig, axs = plt.subplots(2) axs[0].bar(['A', 'B'], [7, 8]) # 条形 axs[1].scatter([1, 2], [9, 10]) # 散点 for ax in fig.get_axes(): ax.label_outer() # 只显示外侧刻度标签 plt.tight_layout() # 调整间距防止重叠 plt.show() ``` #### 特殊类型表展示 除了常规的一维曲线之外,还可以利用内置函数快速生成诸如直方、饼状甚至是三维曲面等多种形式的数据表示方法[^4]。 ```python from mpl_toolkits.mplot3d import Axes3D xn = np.linspace(-5, 5, 100) yn = np.linspace(-5, 5, 100) zn = np.sin(np.sqrt(xn ** 2 + yn[:, None] ** 2)) X, Y = np.meshgrid(xn, yn) Z = zn.reshape(len(yn), len(xn)) fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(projection='3d') surf = ax.plot_surface(X, Y, Z, cmap='viridis') fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值