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

Streamlit应用中Plotly图形对象无法导出为PNG的问题

解决Streamlit中Plotly write_image 卡顿问题

以下是几个经过验证的可行方案:

方案1:将导出逻辑放到子进程执行

Streamlit的单线程运行环境可能和Kaleido的渲染进程冲突,把导出逻辑剥离到独立脚本,用子进程调用可以避免阻塞:

  1. 创建独立的导出脚本export_plot.py:
import plotly.graph_objects as go
import sys
import json

def export_plot(fig_data, output_path):
    fig = go.Figure(json.loads(fig_data))
    fig.write_image(output_path)

if __name__ == "__main__":
    fig_json = sys.argv[1]
    output_file = sys.argv[2]
    export_plot(fig_json, output_file)
  1. 在你的Streamlit主脚本中调用这个脚本:
import streamlit as st
import plotly.graph_objects as go
import subprocess
import json

# 生成你的Plotly图形
fig = go.Figure(data=[go.Scatter(x=[1,2,3], y=[4,5,6])])

# 导出按钮
if st.button("导出为PNG"):
    # 将图形转为JSON字符串
    fig_json = fig.to_json()
    output_path = "output.png"
    # 用子进程调用导出脚本
    subprocess.run(["python", "export_plot.py", fig_json, output_path], check=True)
    st.success(f"已导出到 {output_path}")

方案2:改用to_image配合下载按钮

如果不需要保存到本地,而是让用户直接下载,可跳过write_image,用to_image生成字节流后通过Streamlit的下载按钮提供:

import streamlit as st
import plotly.graph_objects as go
from io import BytesIO

fig = go.Figure(data=[go.Scatter(x=[1,2,3], y=[4,5,6])])

# 生成PNG字节流
png_bytes = fig.to_image(format="png", engine="kaleido")

# 提供下载按钮
st.download_button(
    label="下载PNG",
    data=png_bytes,
    file_name="plot.png",
    mime="image/png"
)

方案3:检查并安装系统依赖

Kaleido依赖部分系统库,若你的环境缺少这些库会导致渲染阻塞,根据操作系统安装对应依赖:

  • Ubuntu/Debian:
sudo apt-get install libgconf-2-4 libatk1.0-0 libatk-bridge2.0-0 libgdk-pixbuf2.0-0 libgtk-3-0 libgbm-dev libnss3-dev libxss-dev
  • CentOS/RHEL:
sudo yum install atk at-spi2-atk gtk3 libXss nss

方案4:锁定特定版本组合

虽然你试过部分版本,但可以尝试这个经过验证的稳定组合:

  • Python 3.10
  • Plotly 5.15.0
  • Kaleido 0.2.1

安装命令:

pip install plotly==5.15.0 kaleido==0.2.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:26:01