情节:如何使用情节和情节表达来绘制回归线? [英] Plotly: How to plot a regression line using plotly and plotly express?
问题描述
我有一个数据帧df,其列为pm1和pm25.我想显示这两个信号之间的相关性的图表(带有Plotly).到目前为止,我已经设法显示了散点图,但是我没有设法画出信号之间的相关性的拟合线.到目前为止,我已经尝试过:
分母= df.pm1 ** 2-df.pm1.mean()* df.pm1.sum()打印('分母',分母)m =(df.pm1.dot(df.pm25)-df.pm25.mean()* df.pm1.sum())/分母b =(df.pm25.mean()* df.pm1.dot(df.pm1)-df.pm1.mean()* df.pm1.dot(df.pm25))/分母y_pred = m * df.pm1 + blineOfBestFit = go.Scattergl(x = df.pm1,y = y_pred,name =最合适的线",线=字典(颜色=红色",))数据= [dataPoints,lineOfBestFit]Figure = go.Figure(data = data)Figure.show()
情节:
如何正确绘制lineOfBestFit?
更新1:
现在,以情节表示的方式可以处理
如果您希望回归线脱颖而出,则可以通过以下方式直接编辑线的颜色:
fig.data [1] .line.color ='红色'
您可以通过访问诸如 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")
那那些长格式呢?那就是密谋表达揭示其某些真正力量的地方.如果以内置数据集 px.data.gapminder
为例,则可以通过指定 color ="continent"
来触发一组国家/地区的各行:
完整的长格式代码段
import plotly.express as pxdf = px.data.gapminder().query(年份== 2007")图= px.scatter(df,x ="gdpPercap",y ="lifeExp",color =大陆",趋势线="lowess")图show()
如果您希望在模型选择和输出方面具有更大的灵活性,可以随时使用我对下面这篇文章的原始回答.但是首先,这是我回答开始时这些示例的完整摘录:
完整的数据段摘录
直接导入plotly.graph_objects导入plotly.express为px导入statsmodels.api作为sm将熊猫作为pd导入将numpy导入为np导入日期时间# 数据np.random.seed(123)numdays = 20X =(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})#回归图#fig = px.scatter(df,x ='X',y ='Y',trendline ="ols")图= px.scatter(df,x ='X',y ='Y',趋势线="lowess")#使回归线突出fig.data [1] .line.color ='红色'#绘图布局fig.update_layout(xaxis_title ='X',yaxis_title ='Y')图show()
原始答案:
对于回归分析,我喜欢使用 statsmodels.api
或 sklearn.linear_model
.我也喜欢在熊猫数据框中同时组织数据和回归结果.这是一种以一种干净有序的方式来做您想要的事情的方法:
使用sklearn或stats模型进行绘制:
使用sklearn的代码:
从sklearn.linear_model 导入LinearRegression随地导入plotly.graph_objects将熊猫作为pd导入将numpy导入为np导入日期时间# 数据np.random.seed(123)numdays = 20X =(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})#回归reg = LinearRegression().fit(np.vstack(df ['X']),Y)df ['bestfit'] = reg.predict(np.vstack(df ['X']))#绘图设置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 ='最合适的线',x = X,y = df ['最合适的'],mode ='线'))#绘图布局fig.update_layout(xaxis_title ='X',yaxis_title ='Y')图show()
使用统计模型的代码:
直接导入plotly.graph_objects导入statsmodels.api作为sm将熊猫作为pd导入将numpy导入为np导入日期时间# 数据np.random.seed(123)numdays = 20X =(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})#回归df ['bestfit'] = sm.OLS(df ['Y'],sm.add_constant(df ['X'])).fit().fittedvalues#绘图设置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 ='最合适的线',x = X,y = df ['最合适的'],mode ='线'))#绘图布局fig.update_layout(xaxis_title ='X',yaxis_title ='Y')图show()
I have a dataframe, df with the columns pm1 and pm25. I want to show a graph(with Plotly) of how correlated these 2 signals are. So far, I have managed to show the scatter plot, but I don't manage to draw the fit line of correlation between the signals. So far, I have tried this:
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()
Plot:
How can I make the lineOfBestFit to be drawn properly?
Update 1:
Now that plotly express handles data of both long and wide format (the latter in your case) like a breeze, the only thing you need to plot a regression line is:
fig = px.scatter(df, x='X', y='Y', trendline="ols")
Complete code snippet for wide data at the end of the question
If you'd like the regression line to stand out, you can edit the line color directly through:
fig.data[1].line.color = 'red'
You can access regression parameters like alpha
and beta through
:
model = px.get_trendline_results(fig)
alpha = model.iloc[0]["px_fit_results"].params[0]
beta = model.iloc[0]["px_fit_results"].params[1]
And you can even request non-linear fit through:
fig = px.scatter(df, x='X', y='Y', trendline="lowess")
And what about those long formats? That's where plotly express reveals some of its real powers. If you take the built-in dataset px.data.gapminder
as an example, you can trigger individual lines for an array of countries by specifying color="continent"
:
Complete snippet for long format
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()
And if you'd like even more flexibility with regards to model choice and output, you can always resort to my original answer to this post below. But first, here's a complete snippet for those examples at the start of my answer:
Complete snippet for wide data
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()
Original answer:
For regression analysis I like to use statsmodels.api
or sklearn.linear_model
. I also like to organize both the data and regression results in a pandas dataframe. Here's one way to do what you're looking for in a clean and organized way:
Plot using sklearn or statsmodels:
Code using 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()
Code using 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()
这篇关于情节:如何使用情节和情节表达来绘制回归线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!