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

如何在matplotlib.figure的同一子图中绘制多组数据集并返回Figure对象

问题原因

你的猜测正确,重复调用fig.add_subplot(111)会在同一位置重复创建子图对象,覆盖前一次的子图及其中的绘图内容,无法实现多组数据叠加展示。

正确实现方案

你只需要提前取出对应位置的子图(Axes)对象,通过该对象多次调用plot()方法即可在同一个子图中叠加多组数据集,修改后的参考代码如下:

import matplotlib.pyplot as plt
from matplotlib.figure import Figure

# 需提前定义好dataA、dataB、time三个可迭代数据对象
def getfig():
    fig = plt.Figure(figsize=(5, 4), dpi=100)
    # 取出111位置的子图对象存入变量ax
    ax = fig.add_subplot(111)
    # 同一子图对象多次调用plot方法,叠加绘制不同数据集
    ax.plot(time, dataA, label='dataA')
    ax.plot(time, dataB, label='dataB')
    # 可选优化:添加坐标轴说明、图例区分不同数据
    ax.set_xlabel('时间')
    ax.set_ylabel('数值')
    ax.legend()
    return fig

注意:matplotlib的plot()方法默认参数顺序为plot(x轴数据, y轴数据),如果你需要将time作为横轴展示,原写法的参数顺序是颠倒的,可根据你的实际需求调整参数顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 16:30:01