gpt4 book ai didi

python - Plotly:如何使用plotly和plotlyexpress绘制回归线?

转载 作者:行者123 更新时间:2023-12-01 06:59:14 29 4
gpt4 key购买 nike

我有一个数据框 df,其中包含 pm1 和 pm25 列。我想用一张图表(用 Plotly)显示这两个信号的相关程度。到目前为止,我已经成功地显示了散点图,但我无法绘制信号之间相关性的拟合线。到目前为止,我已经尝试过:

denominator=df.pm1**2-df.pm1.mean()*df.pm1.sum()
print('denominator',denominator)
m=(df.pm1.dot(df.pm25)-df.pm25.mean()*df.pm1.sum())/denominator
b=(df.pm25.mean()*df.pm1.dot(df.pm1)-df.pm1.mean()*df.pm1.dot(df.pm25))/denominator
y_pred=m*df.pm1+b


lineOfBestFit = go.Scattergl(
x=df.pm1,
y=y_pred,
name='Line of best fit',
line=dict(
color='red',
)
)

data = [dataPoints, lineOfBestFit]
figure = go.Figure(data=data)

figure.show()

plotly :

enter image description here

如何才能正确绘制 lineOfBestFit?

最佳答案

更新 1:

现在 Plotly Express 可以处理 long and wide format 的数据(在你的情况下是后者)就像微风一样,你唯一需要绘制回归线的是:

fig = px.scatter(df, x='X', y='Y', trendline="ols")

问题末尾的宽数据的完整代码片段

enter image description here

如果您希望回归线突出,您可以在以下位置指定trendline_color_override:

fig = `px.scatter([...], trendline_color_override = 'red') 

或者在构建图形后包括线条颜色:

fig.data[1].line.color = 'red'

enter image description here

您可以通过访问回归参数,例如alpha和beta:

model = px.get_trendline_results(fig)
alpha = model.iloc[0]["px_fit_results"].params[0]
beta = model.iloc[0]["px_fit_results"].params[1]

您甚至可以通过以下方式请求非线性拟合:

fig = px.scatter(df, x='X', y='Y', trendline="lowess")

enter image description here

那么那些长格式呢?这就是 Plotly Express 展现其真正威力的地方。如果以内置数据集 px.data.gapminder 为例,您可以通过指定 color="Continental" 来触发一组国家/地区的单独行:

enter image description here

长格式的完整片段

import plotly.express as px

df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", trendline="lowess")
fig.show()

如果您希望在模型选择和输出方面具有更大的灵 active ,您可以随时引用我对下面这篇文章的原始回答。但首先,这是我更新的答案开头的这些示例的完整片段:

宽数据的完整片段

import plotly.graph_objects as go
import plotly.express as px
import statsmodels.api as sm
import pandas as pd
import numpy as np
import datetime

# data
np.random.seed(123)
numdays=20
X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
df = pd.DataFrame({'X': X, 'Y':Y})

# figure with regression
# fig = px.scatter(df, x='X', y='Y', trendline="ols")
fig = px.scatter(df, x='X', y='Y', trendline="lowess")

# make the regression line stand out
fig.data[1].line.color = 'red'

# plotly figure layout
fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')

fig.show()
<小时/>

原始答案:

对于回归分析,我喜欢使用 statsmodels.apisklearn.linear_model。我还喜欢在 pandas 数据框中组织数据和回归结果。这是一种以干净、有组织的方式完成您正在寻找的事情的方法:

使用 sklearn 或 statsmodels 进行绘图:

enter image description here

使用 sklearn 编写代码:

from sklearn.linear_model import LinearRegression
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import datetime

# data
np.random.seed(123)
numdays=20

X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
df = pd.DataFrame({'X': X, 'Y':Y})

# regression
reg = LinearRegression().fit(np.vstack(df['X']), Y)
df['bestfit'] = reg.predict(np.vstack(df['X']))

# plotly figure setup
fig=go.Figure()
fig.add_trace(go.Scatter(name='X vs Y', x=df['X'], y=df['Y'].values, mode='markers'))
fig.add_trace(go.Scatter(name='line of best fit', x=X, y=df['bestfit'], mode='lines'))

# plotly figure layout
fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')

fig.show()

使用 statsmodels 的代码:

import plotly.graph_objects as go
import statsmodels.api as sm
import pandas as pd
import numpy as np
import datetime

# data
np.random.seed(123)
numdays=20

X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()

df = pd.DataFrame({'X': X, 'Y':Y})

# regression
df['bestfit'] = sm.OLS(df['Y'],sm.add_constant(df['X'])).fit().fittedvalues

# plotly figure setup
fig=go.Figure()
fig.add_trace(go.Scatter(name='X vs Y', x=df['X'], y=df['Y'].values, mode='markers'))
fig.add_trace(go.Scatter(name='line of best fit', x=X, y=df['bestfit'], mode='lines'))


# plotly figure layout
fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')

fig.show()

关于python - Plotly:如何使用plotly和plotlyexpress绘制回归线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58708230/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com