plotly - 如何使用 plotly express 添加置信区间 fillcontour?

标签 plotly seaborn plotly-python confidence-interval trendline

我正在使用 plotly express 添加趋势线,现在如何像 seaborn regplot() 一样绘制置信区间,


df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.show()

enter image description here

最佳答案

Plotly 没有内置置信带。但是,既然你想要像 seaborn regplot 这样的东西,你可以直接使用 regplot,提取代表上带和下带的数组,然后创建可视化。

唯一的问题是,为了从 regplot 中提取置信带,您需要指定 binwidth,如 this answer 中所述。 .对于 tips 数据集,我使用 binwidth 为 5 以确保在每个 bin 中有足够的点来创建置信带(如果使用 binwidth 为 1,则不会为数据的稀疏区域计算置信带)

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")

## use binning so that we can access the confidence intervals
binwidth = 5
x_max, x_min = max(df["total_bill"]), min(df["total_bill"])
x_bins = np.arange(x_min, x_max, binwidth)
sns.regplot(x="total_bill", y="tip", x_bins=x_bins, data=df, x_ci=95, fit_reg=None)

ax = plt.gca()
x = [line.get_xdata().min() for line in ax.lines]
y_lower = [line.get_ydata().min() for line in ax.lines]
y_upper = [line.get_ydata().max() for line in ax.lines]

fig.add_trace(go.Scatter(
    x=x+x[::-1], # x, then x reversed
    y=y_upper+y_lower[::-1], # upper, then lower reversed
    fill='toself',
    fillcolor='rgba(0,100,80,0.2)',
    line=dict(color='rgba(255,255,255,0)'),
    hoverinfo="skip",
    showlegend=False
))

fig.show()

enter image description here

关于plotly - 如何使用 plotly express 添加置信区间 fillcontour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71211139/

相关文章:

python - 停止 seaborn 在彼此之上绘制多个图形

python - Plotly:如何使用 Plotly Express 组合散点图和线图?

python - 如何从 Pandas 数据框中的每一列创建子图

r - plotly 等值线图 : display country names

python - 如何在X轴上添加水平滚动条?

python - 更改轴以在seaborn中使用对数刻度

r - 在绘图中添加水平滚动条

python - 在 Seaborn Jointplot 上绘制对角线(相等线)

python - 如何使用绘图等值线根据百分比更改颜色,美国 map ?

machine-learning - 绘图显示 AWS Sagemaker JupyterLab 中的空白图表