Rob*_*Rob 3 python bokeh holoviews pyviz
我正在使用 xarray 数据集创建散点图
scat = ds.hvplot.scatter(x='a', y='b', groupby='c', height=900, width=900)
Run Code Online (Sandbox Code Playgroud)
如何向该图中添加回归线?
我也使用它来设置图中的一些属性,我可以在钩子函数中添加斜率,但我无法弄清楚如何从 plot.state 访问 x 和 y。这也可能是完全错误的做法。
scat = scat.opts(hooks=[hook])
def hook(plot, element):
print('plot.state: ', plot.state)
print('plot.handles: ', sorted(plot.handles.keys()))
par = np.polyfit(x, y, 1, full=True)
gradient=par[0][0]
y_intercept=par[0][1]
slope = Slope(gradient=gradient, y_intercept=y_intercept,
line_color='orange', line_dash='dashed', line_width=3.5)
plot.state.add_layout(slope)
scat = scat.opts(hooks=[hook])
Run Code Online (Sandbox Code Playgroud)
HoloViews >= 1.13现在支持向绘图添加回归线,因此您不再需要挂钩。
1) 您可以通过指定关键字slope 和y_intercept 自己添加回归线:
gradient = 2
y_intercept = 15
# create random data
xpts = np.arange(0, 20)
ypts = gradient * xpts + y_intercept + np.random.normal(0, 4, 20)
scatter = hv.Scatter((xpts, ypts))
# create slope with hv.Slope()
slope = hv.Slope(gradient, y_intercept)
scatter.opts(size=10) * slope.opts(color='red', line_width=6)
Run Code Online (Sandbox Code Playgroud)
2) 或者你可以让 HoloViews 为你计算它hv.Slope.from_scatter():
normal = hv.Scatter(np.random.randn(20, 2))
normal.opts(size=10) * hv.Slope.from_scatter(normal)
Run Code Online (Sandbox Code Playgroud)
结果图:
绘图钩子有两个参数,第二个是正在显示的元素。由于元素包含正在显示的数据,我们可以编写一个回调来使用该dimension_values方法计算斜率,以获取数据中“a”和“b”维度的值。此外,为了避免多次添加坡度字形,我们可以将其缓存在绘图上并更新其属性:
def hook(plot, element):
x, y = element.dimension_values('a'), element.dimension_values('b')
par = np.polyfit(x, y, 1, full=True)
gradient=par[0][0]
y_intercept=par[0][1]
if 'slope' in plot.handles:
slope = plot.handles['slope']
slope.gradient = gradient
slope.y_intercept = y_intercept
else:
slope = Slope(gradient=gradient, y_intercept=y_intercept,
line_color='orange', line_dash='dashed', line_width=3.5)
plot.handles['slope'] = slope
plot.state.add_layout(slope)
Run Code Online (Sandbox Code Playgroud)