# -*- coding: utf-8 -*-
"""Cumulative EvolutionMXPL

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1zc8LS8A0W9WgrYrwMnrsR7qMlldYJYZh
"""



import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv("https://catalog.ourworldindata.org/garden/covid/latest/testing/testing.csv", parse_dates=["date"])

df = (
    df[df["country"].isin(["Mexico", "Poland"])]
      .dropna(subset=["total_tests_per_thousand"])
      .copy()
)


df["period"] = df["date"].dt.to_period("M").astype(str)

monthly = (
    df.groupby(["country", "period"], as_index=False)
      .last()           # last record of each month
      .sort_values(["period", "country"])
)

periods  = monthly["period"].unique()
countries = ["Mexico", "Poland"]


fig_line = go.Figure()

# Empty traces that will grow over frames
for country in countries:
    fig_line.add_trace(go.Scatter(
        x=[], y=[],
        mode="lines+markers",
        name=country
    ))

# Frames: from earliest to latest period, accumulating the series
frames = []
for period in periods:
    data = []
    for c in countries:
        sub = monthly[(monthly.country == c) & (monthly.period <= period)]
        data.append(go.Scatter(
            x=sub["period"],
            y=sub["total_tests_per_thousand"],
            mode="lines+markers",
            name=c
        ))
    frames.append(go.Frame(name=period, data=data))

fig_line.frames = frames

# Play / pause buttons and slider
fig_line.update_layout(
    title="Cumulative Evolution of Tests per Thousand Inhabitants\n(Mexico vs Poland)",
    xaxis_title="Month",
    yaxis_title="Tests per Thousand",
    updatemenus=[{
        "type": "buttons",
        "showactive": False,
        "y": 1.25, "x": 1, "xanchor": "right",
        "buttons": [
            {"label": "▶", "method": "animate",
             "args": [None,
                      {"frame": {"duration": 600, "redraw": True},
                       "transition": {"duration": 300},
                       "fromcurrent": True}]},
            {"label": "⏸", "method": "animate",
             "args": [[None],
                      {"frame": {"duration": 0, "redraw": False},
                       "mode": "immediate"}]}
        ]
    }],
    sliders=[{
        "steps": [
            {"label": p, "method": "animate",
             "args": [[p],
                      {"frame": {"duration": 0, "redraw": True},
                       "mode": "immediate"}]}
            for p in periods
        ],
        "currentvalue": {"prefix": "Month: "}
    }]
)
fig_line.show()
html_plots.append(fig_line.to_html(full_html=False, include_plotlyjs=False, default_height='500px', default_width='100%'))

