Covid Cases & Deaths Graph for U.S
Making a vertically concatenated layered chart. The layered chart comprises a bar chart of new cases, a line and area chart of a week's average of COVID-19 cases and deaths in the U.S for the vertical charts respectively.
The graph that we will learn to make today is from the NYT article on Coronavirus in the U.S
import altair as alt
import pandas as pd
url = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv"
usdf = pd.read_csv(url)
alt.renderers.set_embed_options(actions=False)
usdf['new_deaths'] = usdf['deaths'].diff()
usdf['new_cases'] = usdf['cases'].diff()
# Bar Chart
bar = alt.Chart().mark_bar(size=5,opacity=0.2,color='gray').encode(
x=alt.X('date:T'),
y=alt.Y('new_deaths:Q')
)
# Area Chart
area = alt.Chart().mark_area(fill='gray', fillOpacity=0.15).transform_window(
rolling_average='mean(new_deaths)',
frame=[-6,0] # NYT uses [-6,0] for their average NOT [-7,0]
).encode(
x='date:T',
y='rolling_average:Q'
)
# Line Chart
line = area.mark_line(**{"color": "black", "opacity": 0.7, "strokeWidth": 3})
# Chart of deaths
deaths = (bar+area+line).properties(width=800, title="Deaths")
# Bar Chart
bar2 = alt.Chart().mark_bar(size=5,opacity=0.2,color='red').encode(
x=alt.X('date:T'),
y=alt.Y('new_cases:Q')
)
# Area Chart
area2 = alt.Chart().mark_area(fill='red', fillOpacity=0.15).transform_window(
rolling_average='mean(new_cases)',
frame=[-6,0] # NYT uses [-6,0] for their average NOT [-7,0]
).encode(
x='date:T',
y='rolling_average:Q'
)
# Line Chart
line2 = area2.mark_line(**{"color": "red", "opacity": 0.7, "strokeWidth": 3})
cases = (bar2+area2+line2).properties(width=800, title="Cases")
# Vertically concatenate the charts
alt.vconcat(cases, deaths, data=usdf).configure_axis(
grid=False,
title=None
).configure_view(
strokeWidth=0
)
Possible other ways to do this -
- Repeat Chart
- Facet Chart https://altair-viz.github.io/user_guide/compound_charts.html