[很久以后......发布以防对其他人有价值]
这是一种可行的方法,但我想有更简单的方法......
## 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 --> 面板
## 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
需要hvplot version >= 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}')
对于正在更改小部件状态的“实时”更新,可以检查,例如
面板#Links
(选项 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())
使用版本:
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