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()