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

如何在Streamlit中用Plotly实现交互式regplot?

解决Streamlit中Plotly交互式回归散点图的报错问题

问题原因

你遇到的"Figure" attribute has no attribute "savefig"错误,是因为误用了Streamlit的图表渲染方法:st.pyplot()仅支持渲染Matplotlib生成的图表,而你传入的是Plotly的Figure对象,两者不兼容。

可行实现方案

改用Streamlit专门为Plotly提供的st.plotly_chart()方法来渲染图表,完整代码示例如下:

import streamlit as st
import plotly.express as px
import pandas as pd

# 加载你的DataFrame(替换成实际数据加载逻辑)
# data = pd.read_csv("your_dataset.csv")

# 生成带OLS趋势线的交互式散点图
fig = px.scatter(
    data,
    x='Likes',
    y='Views',
    trendline='ols',
    trendline_color_override='red'
)

# 用Plotly专用方法渲染图表
st.plotly_chart(fig, use_container_width=True)

补充说明

  • use_container_width=True是可选参数,能让图表自适应Streamlit页面的容器宽度,优化展示效果。
  • Plotly的trendline='ols'会自动计算并添加普通最小二乘回归趋势线,完全满足你需要的regplot功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:50:21