# check out https://github.com/mckinsey/vizro for more info about Vizro
# and checkout https://vizro.readthedocs.io/en/stable/ for documentation
import pandas as pd
import plotly.express as px
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.models.types import capture
# Transform the data -----------------------------------------------------------
appearances = pd.read_csv(
"https://raw.githubusercontent.com/plotly/Figure-Friday/main/2024/week-29/ewf_appearances.csv"
)
appearances = appearances[appearances["division"].str.contains("Women's Super League")]
appearances = appearances.sort_values(["date"]).reset_index(drop=True)
dfg = []
for g, df in appearances.groupby(["team_id", "season"]):
df["tgames"] = 1
df["tpoints"] = df["points"].cumsum()
df["tgames"] = df["tgames"].cumsum()
dfg.append(df)
appearances = (
pd.concat(dfg, ignore_index=True).sort_values(["date", "tgames"], ascending=[True, False]).reset_index(drop=True)
)
SEASON = "2022-2023"
df = appearances[(appearances["season"] == SEASON)]
XMAX = df["tpoints"].max() + 1
# Create custom chart -----------------------------------------------------------
@capture("graph")
def chart_animation(data_frame, team_x: str = "Manchester City Women"):
# Create a color column to highlight the selected team
data_frame["color"] = data_frame["team_name"].apply(lambda x: "team_x" if x == team_x else "other_teams")
fig1 = px.bar(
data_frame,
y="team_name",
x="tpoints",
color="color",
orientation="h",
animation_frame="tgames",
range_x=[0, XMAX],
title=f"Women's Super League standings in season {SEASON}",
color_discrete_map={"team_x": "#4361ee", "other_teams": "#ced4da"},
)
for k, frm in enumerate(fig1.frames):
frm["layout"].update(
title_text=f"Women's Super League standings in season" f" {SEASON}<br><sup>after {k + 1:2d} games</sup>"
)
sliders = [
dict(
currentvalue={"prefix": "Games played: "},
)
]
fig1.update_layout(
yaxis_title=None,
xaxis_title="Total Points",
yaxis={"categoryorder": "total ascending"},
showlegend=False,
sliders=sliders,
title_pad_t=24,
)
return fig1
page = vm.Page(
title="Figure Friday Week 29 - English Women's Football ⚽",
components=[
vm.Graph(figure=chart_animation(data_frame=df), id="chart-animation"),
],
controls=[
vm.Parameter(
targets=["chart-animation.team_x"],
selector=vm.Dropdown(
multi=False,
options=list(df["team_name"].unique()),
value="Manchester City Women",
title="Select a team to highlight:",
),
),
],
)
dashboard = vm.Dashboard(pages=[page], theme="vizro_light")
Vizro().build(dashboard).run()