Plotly生成多张重复的图表
最小可复现示例:
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()
不知为何,它会生成该图的三个副本。有人知道如何阻止这种情况的发生吗?
我有如下代码:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
但我需要将它应用到其他数据。Plotly是否有某种设置会导致这种情况?
另外,pio.renders.default = plotly_mimetype+notebook 也可能是造成这种情况的原因吗?
解决方案
看起来使用方法链可以解决这个问题。换句话说,把 fig.update_layout(title_font_size=24) 替换为 fig = fig.update_layout(title_font_size=24),下一行也同样替换为 fig = fig.update_layout(title_font_size=24)。
fig = px.bar(filtered_AFG, x='year',
y='gdp_per_c',
color='Scenario',
barmode='group'
)
fig = fig.update_layout(title_font_size=24)
fig = fig.update_xaxes(showgrid=True)
fig.show()
完整的测试代码:
import plotly.express as px
import pandas as pd
import io
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
s = """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"""
filtered_AFG = pd.read_csv(io.StringIO(s), sep='\s+')
fig = px.bar(filtered_AFG, x='year',
y='gdp_per_c',
color='Scenario',
barmode='group'
)
fig = fig.update_layout(title_font_size=24)
fig = fig.update_xaxes(showgrid=True)
fig.show()
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。