使用Python Plotly导出图片时代码挂起问题求助
问题:Plotly静态图片导出时脚本挂起
我正在编写从Google Sheets导出数据并生成可视化图表的Python代码,已经用Plotly成功生成可视化图表,能在浏览器正常显示并手动下载。但用Plotly静态图片导出功能实现自动化导出时遇到问题:代码在图片保存过程中挂起,无任何错误或调试信息,生成第一个图表后就卡住,脚本包含循环生成多个图表的逻辑。
代码片段
for area, group_df in df.groupby('area'): fig = go.Figure() for cl_name in group_df["cluster_name"].unique(): color_group = group_df[group_df["cluster_name"] == cl_name] trace = go.Scatter( y=color_group["keyword"], x=color_group["count"], mode="markers", marker=dict( size=color_group["count"] / 15, color=color_group["color"], line=dict( width=2, color="grey" ) ), name=f"{cl_name}" ) fig.add_trace(trace) text_scatter = go.Scatter( y = group_df["keyword"], x = group_df["count"], mode = "text", text = group_df["keyword"].apply(lambda x: x if len(x) < 15 else x[:5] + "\\" + x[-5:]), textposition='top center', showlegend = False ) fig.add_trace(text_scatter) fig.update_layout( title = "Area - " + area, xaxis = dict(showgrid=False, showticklabels=False), yaxis = dict(showgrid=False, showticklabels=False), plot_bgcolor = "white", annotations = [ # Footer dict( x=0.95, y=0.005, text= "Footer", showarrow=False, xref="paper", yref="paper", font=dict(size=24, color="gray") ) ] ) # Shows the graph fig.show() # Creates dir if it's doesn't exist if not os.path.exists("images"): os.mkdir("images") # Saves image # Hangs HERE fig.write_image(f"images/{area}.jpeg", width=800, height=600)
已做排查
- 尝试调试,但进程在输出调试信息前就停止,VS Code和PyCharm均出现此问题
- 移除图表中的额外轨迹,问题未解决
- 重启电脑、重装Python,问题依旧
- 调试时发现MainThread处于运行状态,但Thread-6正在执行_collect_standard_error
可能的原因及解决建议
- 依赖缺失或版本不兼容:Plotly的
write_image依赖kaleido(或已废弃的orca),先确认kaleido是否安装:执行pip install kaleido,若已安装,尝试升级到最新版本:pip install --upgrade kaleido plotly - 内存未及时释放:循环生成图表时,未清理旧的fig对象导致内存累积。每次保存图片后添加以下代码强制回收:
import gc del fig gc.collect() - 路径或权限问题:检查
images目录是否有写入权限,或路径中是否包含特殊字符。建议改用绝对路径保存,示例:import os save_path = os.path.join(os.getcwd(), "images", f"{area}.jpeg") fig.write_image(save_path, width=800, height=600) - 图表元素阻塞渲染:文本标签(尤其是处理后的长文本)可能导致渲染卡住。暂时注释掉
text_scatter轨迹,测试是否能正常保存,逐步定位问题元素 - kaleido进程僵死:kaleido作为后台进程可能出现异常,尝试手动调用kaleido scope来保存图片:
from kaleido.scopes.plotly import PlotlyScope scope = PlotlyScope() with open(f"images/{area}.jpeg", "wb") as f: f.write(scope.transform(fig, format="jpeg", width=800, height=600))
内容的提问来源于stack exchange,提问作者Good Morning
相关产品推荐
相关产品推荐

