如何在HoloViews中获取小部件"handler"

5
创建基于xArray数据的HoloViews绘图(QuadMesh)时,任何缺失的维度都会自动创建小部件(例如滑块),以便于数据探索。例如:
hv_ds = hv.Dataset(data)    
plot = hv_ds.to(hv.QuadMesh, kdims=["lon", "lat"], vdims="depth")

由于数据包含12个月的数据,HoloViews将基于经度和纬度创建QuadMesh,使用深度作为值,然后提供一个滑块小部件来选择月份。它将把所有内容放在一个类似于这样的HoloMap中:

HoloMap containing 12 items of type QuadMesh
--------------------------------------------

Key Dimensions: 
     month: 1.0...12.0 
Deep Dimensions: 
     lon: -280.0...80.0 
     lat: -78.0...-44.6 
     depth: 3.5...4796.6 

生成的图表

我想获取“月份滑块小部件”的值以更新另一个图表,但我找不到访问它的方法。没有 plot.get_widget_value() 或类似的东西。有什么想法可以获取指针或处理器吗?

2个回答

1

[若对他人有价值,此处发布多年后的内容...]

这是一种可行的方法,但我想可能有更简单的方法...

## imports
import pandas as pd
import numpy as np
import xarray as xr

import hvplot.xarray
import panel as pn

## generate an xr.DataArray
start_date = '2021-01-01'
time = pd.date_range(start=start_date, periods=12, freq='M')
x,y = np.ogrid[0:512, 0:512]
data = np.random.randn(time.size, x.size, y.size)
coords = dict(time=time, x=x.ravel(), y=y.ravel())
space_time_xr = xr.DataArray(data, coords=coords, dims=list(coords), name='space_time')

选项A:hvPlot --> Panel
## use hvplot to implicitly generate the widget -- there's an alternative 
space_time_hv = space_time_xr.hvplot(x='x', y='y')

## use panel to access the slider
space_time_pn = pn.panel(space_time_hv)

## a pointer to the slider widget
time_slider_pnw = space_time_pn[1][0][0]

## present the viz+widget
space_time_pn

Option A screenshot

选项B:使用.interactive API

需要hvplot版本 >= 0.7

## use .interactive API to generate the widget
space_time_pnw = space_time_xr.interactive.sel(time=pn.widgets.DiscreteSlider).hvplot()

## a pointer to the slider widget
time_slider_pnw = space_time_pnw.widgets().objects[0]

## present the viz+widget
space_time_pnw

使用滑动条互动... 然后可以读取滑动条的当前值:

## get slider current value
current_pnw_value = time_slider_pnw.value

## print the value
print(f'{current_pnw_value}')

为了在小部件状态发生变化时进行“实时”更新,可以检查例如面板#链接

(选项C).interactive +链接示例:标题根据小部件状态进行更新

## use interactive API to generate the widget
time_slider_pnw = pn.widgets.DiscreteSlider(name='time',options=space_time_xr.time.to_series().to_dict())
space_time_pn = space_time_xr.interactive.sel(time=time_slider_pnw).hvplot()

## dynamics markdown
time_md = pn.pane.Markdown(f'## {time_slider_pnw.value:%Y-%m-%d}')

def callback(target, event):
    target.object = f'## {event.new:%Y-%m-%d}'
    
## link
time_slider_pnw.link(time_md, callbacks={'value' : callback} )

## present the time slider value
pn.Column(time_md, space_time_pn.panel(), space_time_pn.widgets())

Option C .interactive + link screenshot

使用版本:
Python version       : 3.7.10

numpy : 1.20.2
xarray: 0.18.0
pandas: 1.2.4

hvplot    : 0.7.1
panel     : 0.11.3
holoviews : 1.14.3
bokeh     : 2.3.1
jupyterlab: 3.0.14

1

我不知道如何在创建小部件和绘图时获取当前值,也许其他人知道。

但是我知道如何在使用面板创建小部件和绘图的示例中获取当前选择的值。如果您像下面的示例一样这样做,那么您只需使用your_selection_widget.value即可获取当前选择的值:

# import libraries
import numpy as np
import pandas as pd

import hvplot
import hvplot.pandas

import holoviews as hv
hv.extension('bokeh', logo=False)

import panel as pn


# create sample data
df = pd.DataFrame({
    'col1': np.random.rand(30),
    'col2': np.random.normal(size=30),
    'category_col': np.random.choice(['category1', 'category2'], size=30)
})

# create widget to select category
category = pn.widgets.Select(options=['category1', 'category2'])

# function that returns a plot depending on the category selected
@pn.depends(category)
def get_plot(category):
    df_selected = df[df['category_col'] == category]
    plot = df_selected.hvplot.scatter(x='col1', y='col2')
    return plot

# show dashboard with selection widget and dynamic plot
pn.Column(
    pn.Row(category),
    get_plot,
)

# get value of current selected category
category.value

你可以在这里找到更多关于如何创建类似这样的交互式仪表板的信息:
https://panel.pyviz.org/gallery/apis/stocks_hvplot.html#gallery-stocks-hvplot

谢谢Sander,当我创建自己的仪表板并可以控制小部件的创建时,这将非常有帮助。我的问题仍然是当小部件被“神奇”地为我创建时... - user12444217
@Sander,我这里复制了你的代码,但是不知道为什么在选择不同类型时绘图没有更新,你知道发生了什么吗? - Amen_90

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接