You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将函数返回的Matplotlib Figure作为新Figure的子图?

解决方案:将已有绘图方法整合为子图

核心问题

你当前的plot1()和plot2()方法会独立创建完整的Figure对象,而Matplotlib中无法直接将一个Figure嵌入另一个Figure的子图中。正确的思路是让绘图方法支持在指定的Axes上绘制,而非每次新建Figure。

修改方案

重构plot1()和plot2(),让它们接受一个外部Axes参数,这样既能保留独立绘图的功能,也能在new_plot()中将它们作为子图复用。

完整修改代码

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np

class SomethingCool():
    def plot1(self, ax=None):
        # 未传入Axes时,创建独立Figure和Axes
        if ax is None:
            fig = plt.figure(figsize=(8,8))  # 修正语法错误:figsize需用括号包裹参数
            gs = GridSpec(1,1,figure=fig)
            ax = fig.add_subplot(gs[0,0])
            fig.set_tight_layout(True)
        else:
            fig = ax.figure  # 从传入的Axes获取所属Figure

        x = np.linspace(0, 10, 100)
        x2 = np.linspace(0, 100, 100)
        y = np.linspace(50,80,100)

        ax.plot(x, y)
        axb = ax.twiny()  # twiny无需传x,默认创建共享y轴的双x轴
        axb.plot(x2,y)

        # 仅独立绘图时显示,整合子图时由new_plot统一控制
        if ax is None:
            fig.show()

        return fig, (ax, axb)

    def plot2(self, ax=None):
        if ax is None:
            fig = plt.figure(figsize=(8,8))
            gs = GridSpec(1,1,figure=fig)
            ax = fig.add_subplot(gs[0,0])
            fig.set_tight_layout(True)
        else:
            fig = ax.figure

        x = np.linspace(0, 20, 100)
        x2 = np.linspace(0, 200, 100)
        y = np.linspace(0,100,100)

        ax.plot(x, y)
        axb = ax.twiny()
        axb.plot(x2,y)

        if ax is None:
            fig.show()

        return fig, (ax, axb)

    def new_plot(self):
        # 创建总Figure和布局:2行2列,第一行占满两列,第二行分左右子图
        fig = plt.figure(figsize=(12, 10))
        gs = GridSpec(2, 2, figure=fig)

        # 第一行绘制正弦曲线
        ax_sin = fig.add_subplot(gs[0, :])
        x = np.linspace(0, np.pi, 100)
        y = np.sin(x)
        ax_sin.plot(x, y)
        ax_sin.set_title('Sin Curve')

        # 第二行左侧子图:传入Axes调用plot1
        ax_plot1 = fig.add_subplot(gs[1, 0])
        self.plot1(ax=ax_plot1)
        ax_plot1.set_title('Plot 1')

        # 第二行右侧子图:传入Axes调用plot2
        ax_plot2 = fig.add_subplot(gs[1, 1])
        self.plot2(ax=ax_plot2)
        ax_plot2.set_title('Plot 2')

        fig.set_tight_layout(True)
        fig.show()

# 测试调用
sc = SomethingCool()
sc.new_plot()

关键改动说明

  • 新增ax参数:让绘图方法支持接收外部Axes,实现绘图逻辑的复用,既可以独立生成Figure,也能作为子图嵌入其他Figure。
  • 修正语法错误:原代码中figsize(8,8)应为figsize=(8,8)。
  • 调整布局结构:将总Figure设为2行2列,满足你把plot1、plot2放在第二行左右子图的需求。
  • 统一显示控制:仅在独立绘图时调用fig.show(),整合子图时由new_plot()统一处理显示逻辑。

内容的提问来源于stack exchange,提问作者Woodywoodleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:45:59