Py.Cafe

panel-org/

altair-brushing

An app demonstrating usage of Altair brushing

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import altair as alt
import pandas as pd
import panel as pn

pn.extension('vega', template='fast')

pn.state.template.title = "Altair Brushing Example"

df = pd.read_json("https://raw.githubusercontent.com/vega/vega/master/docs/data/penguins.json")

brush = alt.selection_interval(name='brush')  # selection of type "interval"

chart = alt.Chart(df).mark_point().encode(
    x=alt.X('Beak Length (mm):Q', scale=alt.Scale(zero=False)),
    y=alt.Y('Beak Depth (mm):Q', scale=alt.Scale(zero=False)),
    color=alt.condition(brush, 'Species:N', alt.value('lightgray'))
).properties(
    width=300,
    height=300
).add_params(
    brush
)

vega_pane = pn.pane.Vega(chart, debounce=10)

def filtered_table(selection):
    if not selection:
        return df.iloc[:0]
    query = ' & '.join(
        f'{crange[0]:.3f} <= `{col}` <= {crange[1]:.3f}'
        for col, crange in selection.items()
    )
    return df.query(query)

pn.Column(
    'Select points on the plot and watch the linked table update.',
    sizing_mode='stretch_width'
).servable()

pn.Row(
    vega_pane,
    pn.Column(
        pn.pane.DataFrame(
            pn.bind(filtered_table, vega_pane.selection.param.brush)
        ),
        height=350
    )
).servable()