holoviews散点图的回归线?

时间:2019-02-21 11:33:22

标签: python bokeh holoviews pyviz

我正在使用xarray数据集创建散点图

scat = ds.hvplot.scatter(x='a', y='b', groupby='c', height=900, width=900)

如何向该图添加回归线?

我还使用它来设置绘图中的某些属性,我可以在hook函数中添加Slope,但是我不知道如何从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])

1 个答案:

答案 0 :(得分:2)

为绘图挂钩提供了两个参数,其中第二个是显示的元素。由于元素包含要显示的数据,因此我们可以编写一个回调,以使用dimension_values方法来计算斜率,以获取数据中“ a”和“ b”维的值。此外,为了避免多次添加Slope字形,我们可以将其缓存在绘图上并更新其属性:

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)
相关问题