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

Plotly生成重复图表问题求助:如何避免重复绘图?

问题:Plotly绘制分组柱状图出现重复图表

用户使用Plotly的px.bar函数绘制分组柱状图时,生成了三个重复图表,以下是相关信息:

可复现示例数据

iso   country      year   gdp_per_c  Scenario
AFG   Afghanistan  2030   0.3890     SSP1-2.6
AFG   Afghanistan  2040   0.6465     SSP1-2.6
AFG   Afghanistan  2030   0.2106     SSP2-4.5    
AFG   Afghanistan  2040   0.3635     SSP2-4.5

绘图代码

fig=px.bar(filtered_AFG, x='year',
           y='gdp_per_c', 
           color='Scenario',
           barmode='group'
)
fig.update_layout(title_font_size=24)
fig.update_xaxes(showgrid=True)
fig.show() 

用户额外设置

IPython交互设置

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Plotly渲染器设置

import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook"

问题原因

这两个设置确实会共同导致重复图表:

  • InteractiveShell.ast_node_interactivity = "all":该设置会让IPython输出所有语句的返回值,而fig.update_layout()、fig.update_xaxes()都会返回修改后的Figure对象,加上fig.show()的渲染,会触发多次绘图。
  • pio.renderers.default = "plotly_mimetype+notebook":这个设置会同时启用两种渲染方式,一次调用生成两个独立的渲染结果,再加上IPython自动渲染返回的Figure对象,最终出现三个重复图表。

解决方法

方法1:调整IPython交互行为

将交互设置改回默认值,仅输出最后一条语句的返回值:

InteractiveShell.ast_node_interactivity = "last_expr"

如果需要保留"all"的交互性,可在不需要输出返回值的语句末尾添加分号;来抑制输出:

fig=px.bar(filtered_AFG, x='year',
           y='gdp_per_c', 
           color='Scenario',
           barmode='group'
)
fig.update_layout(title_font_size=24);  # 抑制返回值输出
fig.update_xaxes(showgrid=True);       # 抑制返回值输出
fig.show() 

方法2:修改Plotly渲染器设置

将渲染器设置为单一类型,避免双重渲染:

import plotly.io as pio
# 选择其中一种即可
pio.renderers.default = "plotly_mimetype"
# 或者
pio.renderers.default = "notebook"

方法3:组合调整

同时修改上述两个设置,从根源上避免重复渲染问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 22:33:09