Py.Cafe

panel-org/

basic-animation

A basic animation app

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import altair as alt
import pandas as pd
import panel as pn

pn.extension("vega") # load the vega/ Altair JavaScript dependencies

BY = "t_manu"  # t_state, t_county, or t_manu
VALUE = "p_cap"

## Extract the data

@pn.cache()  # use caching to only download data once
def get_data():
    return pd.read_csv("https://assets.holoviz.org/panel/tutorials/turbines.csv.gz")

## Transform the data

data = get_data()
min_year = int(data.p_year.min())
max_year = int(data.p_year.max())
max_capacity_by_manufacturer = data.groupby(BY)[VALUE].sum().max()


def get_group_sum(year):
    return (
        data[data.p_year <= year][[BY, VALUE]]
        .groupby(BY)
        .sum()
        .sort_values(by=VALUE, ascending=False)
        .reset_index()
        .head(10)
    )

# Plot the data

def get_plot(year):
    data = get_group_sum(year)
    base = (
        alt.Chart(data)
        .encode(
            x=alt.X(VALUE, scale=alt.Scale(domain=[0, max_capacity_by_manufacturer]), title="Capacity"),
            y=alt.Y(f"{BY}:O", sort=[BY], title="Manufacturer"),
            text=alt.Text(VALUE, format=",.0f"),
        )
        .properties(title=str(year), height=500, width="container")
    )
    return base.mark_bar() + base.mark_text(align="left", dx=2)

# Add widgets

year = pn.widgets.Player(
    value=max_year,
    start=min_year,
    end=max_year,
    name="Year",
    loop_policy="loop",
    interval=300,
    align="center",
)

def pause_player_at_max_year(value):
    if year.value==max_year:
        year.pause()

pn.bind(pause_player_at_max_year, year, watch=True) # Stops the player when max_year is reached.

# Bind the plot to the Player widget

plot = pn.pane.Vega(pn.bind(get_plot, year))

# Layout the components
pn.Column("# Wind Turbine Capacity 1982-2022", plot, year, sizing_mode="stretch_width").servable()