调用Plotly full_figure_for_development时Streamlit崩溃的原因
问题
需要获取Plotly图表当前的x轴和y轴范围,尝试使用Plotly提供的full_figure_for_development()方法,但在Streamlit中运行时应用崩溃冻结,控制台无输出。使用的代码如下:
import streamlit as st import plotly.graph_objects as go import kaleido fig = go.Figure( data=[go.Scatter( mode="markers+text", x=[10,20], y=[20, 10], text=["Point A", "Point B"] )], layout=dict(height=400, width=400, template="none") ) st.plotly_chart(fig) full_fig = fig.full_figure_for_development() print(full_fig)
解决方案
问题根源
full_figure_for_development()用于生成包含所有JavaScript计算默认值的完整图表对象,但它的执行逻辑与Streamlit的图表渲染流程冲突——当Streamlit已经渲染过图表后,再调用该方法会引发资源死锁,导致应用冻结。
修复步骤
- 调整代码执行顺序:先调用
full_figure_for_development()获取完整图表对象,再通过Streamlit渲染图表。 - 精准提取轴范围:无需打印整个
full_fig(内容过多会加重资源负载),直接提取x/y轴的range属性即可。
修改后的代码
import streamlit as st import plotly.graph_objects as go import kaleido fig = go.Figure( data=[go.Scatter( mode="markers+text", x=[10,20], y=[20, 10], text=["Point A", "Point B"] )], layout=dict(height=400, width=400, template="none") ) # 先获取完整图表对象并提取轴范围 full_fig = fig.full_figure_for_development() x_range = full_fig.layout.xaxis.range y_range = full_fig.layout.yaxis.range print(f"X轴范围: {x_range}, Y轴范围: {y_range}") # 再将图表渲染到Streamlit st.plotly_chart(fig)
内容的提问来源于stack exchange,提问作者dwaltsch
相关产品推荐
相关产品推荐

