如何在plotly express scatter中为多种颜色只设置一条趋势线?

2024-04-26 04:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个只有一条趋势线的散点图。Plotly express为点列表中的每种颜色创建不同的趋势线。在

import plotly.express as px

value = [15, 20, 35, 40, 48]
years = [2010, 2011, 2012, 2013, 2014]
colors = ['red', 'red', 'blue', 'blue', 'blue']

fig = px.scatter(
    x=years,
    y=value,
    trendline='ols',
    color=colors
)

fig.show()

有没有办法只为所有点创建一条趋势线?在

绘图:

enter image description here

提前谢谢!在


Tags: import列表value颜色asfigbluered
2条回答

由于您没有特别要求内置的plotlyexpress功能,因此您可以轻松地在px.Scatter()上构建并使用statsmodels.OLSadd_traces(go.Scatter())来获得所需的:

绘图:

enter image description here

代码:

import plotly.express as px
import plotly.graph_objs as go
import statsmodels.api as sm

value = [15, 20, 35, 40, 48]
years = [2010, 2011, 2012, 2013, 2014]
colors = ['red', 'red', 'blue', 'blue', 'blue']

# your original setup
fig = px.scatter(
    x=years,
    y=value,
    color=colors
)

# linear regression
regline = sm.OLS(value,sm.add_constant(years)).fit().fittedvalues

# add linear regression line for whole sample
fig.add_traces(go.Scatter(x=years, y=regline,
                          mode = 'lines',
                          marker_color='black',
                          name='trend all')
                          )
fig

你可以有两种方式:

绘图:

enter image description here

代码更改:只需添加trendline='ols'

^{pr2}$

目前还没有内置功能,不,很不幸!但这是一个好主意,我创建了一个问题,建议将其作为一个补充:https://github.com/plotly/plotly.py/issues/1846

相关问题 更多 >