随着 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_scope
是trace
产生:
情节 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
)