- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数据框 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 :
如何才能正确绘制 lineOfBestFit?
最佳答案
现在 Plotly Express 可以处理 long and wide format 的数据(在你的情况下是后者)就像微风一样,你唯一需要绘制回归线的是:
fig = px.scatter(df, x='X', y='Y', trendline="ols")
问题末尾的宽数据的完整代码片段
如果您希望回归线突出,您可以在以下位置指定trendline_color_override
:
fig = `px.scatter([...], trendline_color_override = 'red')
或者在构建图形后包括线条颜色:
fig.data[1].line.color = 'red'
您可以通过
访问回归参数,例如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")
那么那些长格式呢?这就是 Plotly Express 展现其真正威力的地方。如果以内置数据集 px.data.gapminder
为例,您可以通过指定 color="Continental"
来触发一组国家/地区的单独行:
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.api
或 sklearn.linear_model
。我还喜欢在 pandas 数据框中组织数据和回归结果。这是一种以干净、有组织的方式完成您正在寻找的事情的方法:
使用 sklearn 或 statsmodels 进行绘图:
使用 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/
我想创建这样的情节: 这里我们有两个变量 X = midyear 和 Y = yearend。我想为 Y 的 X 的每个级别创建密度图。 我可以做到这一点,但看起来并不像我想象的那样,特别是情节和线条
我正在尝试在数据框的行上应用公式来获取行中数字的趋势。 下面的示例在使用 .apply 的部分之前一直有效。 df = pd.DataFrame(np.random.randn(10, 4), col
我是一名优秀的程序员,十分优秀!