首页 > 解决方案 > 如何在 plotly express scatter 中只为多种颜色设置一条趋势线?

问题描述

我想创建一个只有一条趋势线的散点图。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()

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

阴谋:

在此处输入图像描述

提前致谢!

标签: pythonplotlyregressionplotly-express

解决方案


随着 Plotly 5.2.1 (2021-08-13)using的发布,px.scatter()您可以指定:

trendline_scope = 'overall'

情节 1 - trendline_scope = 'overall'

在此处输入图像描述

如果趋势线的绿色不符合您的喜好,您可以通过以下方式进行更改:

 trendline_color_override = 'black'

情节 2 -trendline_color_override = 'black'

在此处输入图像描述

另一个选项trendline_scopetrace产生:

情节 3 -trendline_scope = 'trace'

在此处输入图像描述

完整代码:

import plotly.express as px

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip",
                 color="sex",
                 trendline="ols",
                 trendline_scope = 'overall',
#                trendline_scope = 'trace'
                 trendline_color_override = 'black'
                )
fig.show()

旧版本的先前答案:


由于您没有特别要求内置的 plotly express功能,因此您可以轻松构建px.Scatter()并获得您想要statsmodels.OLS的内容add_traces(go.Scatter())

阴谋:

在此处输入图像描述

代码:

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

你可以同时拥有它:

阴谋:

在此处输入图像描述

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

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

推荐阅读