如何使用plotlyexpress添加置信区间fillcontour?

2024-04-26

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


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


Plotly 没有内置置信区间。但是,因为您想要 Seaborn 之类的东西regplot,您可以直接使用regplot,提取代表上下波段的数组,然后在plotly中创建可视化。

唯一的事情是,为了从 regplot 中提取置信带,您需要指定一个binwidth如中所解释的这个答案 https://stackoverflow.com/questions/54868292/extract-mean-and-confidence-intervals-from-seaborn-regplot。对于提示数据集,我使用了 5 的 binwidth 以确保在每个 bin 内有足够的点来创建置信带(如果使用 1 的 binwidth,则不会为数据的稀疏区域计算置信带) )

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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用plotlyexpress添加置信区间fillcontour? 的相关文章

随机推荐