I have plotted COVID-19 cases per day (y) by date (x) and would like to add a few lines/data points in the graph indicating lockdown or emergence of a new variant. How I could do it using plotly? I would like to e.g. add point "First lockdown" for particular date (x-axis). I assume it's quite simple, just couldn't find solution yet (found for matplotlib only). Thanks!
1 Answer
Using COVID as the data to demonstrate.
- lines can be added using
add_vline() - annotations can be added using
add_annotation(). In this example I have chosen to place on y-axis so text does not overlap across significant dates.
import pandas as pd
import plotly.express as px
# get covid data for uk
df = pd.read_csv(
"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv"
)
df["date"] = pd.to_datetime(df["date"])
df = df.loc[df["iso_code"].eq("GBR")]
# get significat dates in UK covid response
df2 = pd.read_csv(
"https://data.london.gov.uk/download/covid-19-restrictions-timeseries/03073b4a-2f5d-4a0a-be90-4fe3d9f609c9/restrictions_summary.csv"
)
df2["date"] = pd.to_datetime(df2["date"], format="%d/%m/%Y")
df2 = df2.loc[df2.select_dtypes("number").sum(axis=1).ge(6)]
# simple line graph
fig = px.line(df, x="date", y="new_cases_smoothed")
# add significant dates and vertical lines and annotations
for n, (i, r) in enumerate(df2.iterrows()):
fig.add_vline(x=r["date"], line_dash="dot")
fig.add_annotation(
x=r["date"], y=n / len(df2), yref="y domain", text=r["restriction"]
)
fig
