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()