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

如何清除Plotly堆叠图表?多报表数据叠加问题求助

问题解决:Plotly报表数据叠加的根源与修复

问题描述

编写生成3份独立报表的Python脚本,向createReport函数传入3个不同字典后,第一份报表显示正常,但后续两份报表会叠加前一份的数据。尝试删除Plotly对象(fig)无效,询问是否有方法清除Plotly对象。

第一份正常报表:显示单一饼图和对应类别的条形图,数据无重复叠加。
存在叠加问题的报表:条形图包含前一份报表的标签与数值,出现数据叠加情况。

问题根源

不是Plotly对象未清除的问题,而是你在函数外部定义了indirectLabels、indirectValues、directLabels、directValues这四个全局列表。每次调用createReport时,函数会持续往这些全局列表里追加数据,而非每次生成新报表时重新初始化空列表,导致后续报表使用累积了多份数据的列表,最终出现叠加。

修复方案

在createReport函数内部初始化这四个列表,确保每次调用函数时使用全新的空列表,避免数据累积:

def createReport(myDict,name):
    # 函数内部初始化空列表,杜绝全局变量累积数据
    indirectLabels = []
    indirectValues = []
    directLabels = []
    directValues = []
    
    for key in myDict:
        if "ER" in key:
            indirectLabels.append(key)
            indirectValues.append(round(myDict[key],2))
        else:
            directLabels.append(key)
            directValues.append(round(myDict[key],2))
    
    pieTotal = [round(sum(myDict.values()),2)]
    myDict['pieTotal'] = pieTotal
    myDict['indirectLabels'] = indirectLabels
    myDict['indirectValues'] = indirectValues
    myDict['directValues'] = directValues
    myDict['directLabels'] = directLabels

    fig = make_subplots(rows=2, cols=2, subplot_titles=('Total Payroll','Indirect Payroll Breakdown','Direct Payroll Breakdown'),
                                         specs=[[{"type": "pie"}, {"type": "bar"}],
                                                [{"colspan": 2}, None]])
    fig.add_trace(go.Pie(
        values=myDict['pieTotal'],
        text=myDict['pieTotal'],
        domain=dict(x=[0, 0.5])), 
        row=1, col=1)
    fig.add_trace(go.Bar(
        y=myDict['indirectValues'],
        text=myDict['indirectValues'],
        x=myDict['indirectLabels']), 
        row=1, col=2)
    fig.add_trace(go.Bar(
        y=myDict['directValues'],
        text=myDict['directValues'],
        x=myDict['directLabels']), 
        row=2, col=1)
    fig.update_layout(
        title_text="Payroll Data MTD: " + name
    )
    fig.show()
    # 无需手动删除fig,函数执行完毕后会被Python自动回收

createReport(constructionDict,'Construction')
createReport(serviceDict,'Service')

额外说明

  • 无需手动删除fig,Python的垃圾回收机制会在函数执行完后自动清理局部变量fig。
  • 尽量避免用全局变量存储临时数据,尤其是在循环或多次调用的函数中,极易出现数据累积问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:52:12