首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建px.scatter后插入趋势线(图)

创建px.scatter后插入趋势线(图)
EN

Stack Overflow用户
提问于 2022-10-13 11:19:38
回答 1查看 48关注 0票数 1

NAME="Ubuntu“VERSION="20.04.3 LTS (焦点Fossa)”

Streamlit,1.12.0版

Python 3.8.10

plotly==5.10.0

我有一个Streamlit仪表板,它使用plotly express制作图表。仪表板允许用户选择不同的选项,图表在动态的情况下使用这些选项重新创建。

其中一个选项是添加趋势线,但是我只在创建无花果(作为px.scatter()的一个选项)时找到了这样做的方法。

是否有方法在调用fig = px.scatter之后添加趋势线?

当前代码:

代码语言:javascript
复制
def control_chart_by_compound(
                  df, 
                  x_column_name, 
                  y_column_name, 
                  trendline = False, 
                  trendlinetype = "ols", 
                  trendline_scope="overall", 
                 ):
    
    def _trendlinescatter():
        try: 
            assert trendlinetype == "ols", "Only Ordinary Least Squares (trendlinetype = 'ols') is currently supported."
            fig = px.scatter(x=x_column_name, 
                             y=y_column_name, 
                             labels={
                                 "x": x_column_name,
                                 "y": y_column_name,
                                 color_column_name: "Compounds"
                             },
                             trendline = trendlinetype, 
                             trendline_scope = trendline_scope, 
                            )
            return fig
        
        except Exception as e:
            err = "Unfortunately I'm unable to create a scatter plot with trendline from columns '{}' and '{}'. (ERROR: {})".format(x_column_name, y_column_name, e) 
            print(err)
            return _notrendlinescatter()
            
    def _notrendlinescatter():
        fig = px.scatter(df, 
                         x=x_column_name, 
                         y=y_column_name, 
                         labels={
                             "x": x_column_name,
                             "y": y_column_name,
                             color_column_name: "Compounds"
                         },
                        )
        return fig
                
    if trendline != False: 
        fig = _trendlinescatter()
    else:
        fig = _notrendlinescatter()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-13 11:43:58

我有一个解决方法来解决这个问题,即添加trendline,然后在默认情况下隐藏它,让用户显示它。尝试更改withTrendline的值

代码语言:javascript
复制
import plotly.express as px

withTrendline = False # value comes from the callback 

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.update_traces(visible=withTrendline, selector=dict(mode="lines")) 
fig.show()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74054901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档