如何使用 plotly express 添加置信区间 fillcontour?
how to add confidence interval fillcontour using plotly express?
我正在使用 plotly express 添加趋势线,现在如何像 seaborn regplot() 那样绘制置信区间,
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.show()
Plotly 没有内置置信带。但是,既然你想要像 seaborn 这样的东西 regplot
,你可以直接使用 regplot,提取代表上下带的数组,然后创建可视化在剧情中。
唯一的问题是,为了从 regplot 中提取置信带,您需要指定 binwidth
,如 中所述。对于 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()
我正在使用 plotly express 添加趋势线,现在如何像 seaborn regplot() 那样绘制置信区间,
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.show()
Plotly 没有内置置信带。但是,既然你想要像 seaborn 这样的东西 regplot
,你可以直接使用 regplot,提取代表上下带的数组,然后创建可视化在剧情中。
唯一的问题是,为了从 regplot 中提取置信带,您需要指定 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()