Special widgets

Traitlet widgets

Widget properties are IPython traitlets. To make changes, the observe method of the widget can be used to register a callback.

Further information can be found at Traitlet events.

[1]:
import bqplot as bq
import ipywidgets as widgets
import numpy as np


### Create random data
size = 2000  # number of rows
scale = 1.0
scaleLocal = 20
np.random.seed(0)
x_data = np.arange(size)
y_data = (
    np.cumsum(np.random.randn(size) * scale)
    + np.random.randn(size) * scaleLocal
)


x_sc = bq.LinearScale()
y_sc = bq.LinearScale()

ax_x = bq.Axis(label="X", scale=x_sc, grid_lines="solid", tick_format="0f")
ax_y = bq.Axis(
    label="Y", scale=y_sc, orientation="vertical", tick_format="0.2f"
)

line1 = bq.Lines(
    x=x_data,
    y=y_data,
    scales={"x": x_sc, "y": y_sc},
    colors=["blue"],
    display_legend=False,
    labels=["y1"],
    stroke_width=1.0,
)

m_fig = dict(left=100, top=50, bottom=50, right=100)
fig = bq.Figure(axes=[ax_x, ax_y], marks=[line1], fig_margin=m_fig)

x_range = widgets.IntRangeSlider(
    value=[min(x_data), max(x_data)],
    min=min(x_data),
    max=max(x_data),
    step=(max(x_data) - min(x_data)) / 100,
    description="X Axis",
    disabled=False,
    continuous_update=False,
    orientation="horizontal",
    readout=True,
)


def updateXAxis(change):
    # Update X-axis min/max value here
    if change["type"] == "change" and change["name"] == "value":
        x_sc.min = change["new"][0]
        x_sc.max = change["new"][1]


x_range.observe(updateXAxis)
widgets.VBox([fig, x_range])

Linking widgets

When synchronising traitlet attributes, there may be a delay due to latency in communication with the server. However, you can also link the widget attributes directly to the link widgets in the browser either unidirectionally or bidirectionally.

These Javascript links are also retained if widgets are embedded in HTML web pages without a kernel.

For more information, see Linking widgets attributes from the client side from the client side.

[2]:
# Sliders to change minimum and maximum valuese on x scale of bqplot figure using jslink
x_rangeMin = widgets.IntSlider(
    min=min(x_data),
    max=max(x_data),
    step=(max(x_data) - min(x_data)) / 100,
    description="Min x scale: ",
    value=x_sc.min,
)
x_rangeMax = widgets.IntSlider(
    min=min(x_data),
    max=max(x_data),
    step=(max(x_data) - min(x_data)) / 100,
    description="Max x scale: ",
    value=x_sc.max,
)

widgets.jslink((x_sc, "min"), (x_rangeMin, "value"))
widgets.jslink((x_sc, "max"), (x_rangeMax, "value"))

widgets.VBox([fig, x_rangeMin, x_rangeMax])