python - 如何在 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()
有没有办法为所有点创建一条趋势线?
阴谋:
提前致谢!
解决方案
随着 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
)
推荐阅读
- pipe - 鱼函数有没有办法从管道读取可选输入?
- c# - xUnit Mock 从 IoC 容器请求新实例
- asynchronous - 有没有办法将 OpenAPI Generator 配置为同步运行?
- batch-file - 批量访问数组的不同方式
- f# - 无法加载文件或程序集 Microsoft.Bcl.AsyncInterfaces
- api - Whatsapp 业务 API 组
- c# - 使用 ASP.NET Core 在运行时托管本地资源
- json - 如何为每个端点提供 API JSON 模式?
- python - 使用随机数生成器为多个操作设置边界限制
- javascript - 一次将多个变量移动到反应中的另一个组件