'Creating Time Series Plots with the countries as subplots
I am stuck when it comes to creating the plots as I don't know how to define the x and y variable. I was planning on making the countries as the x variable and then making the dates for the COVID cases as the y variable. I want to know what is the best way to do this. Furthermore, is there any way to plot each country in a different subplot?
Thank you for the help.
I have attached the following piece of code:
import pandas as pd
cases_raw = pd.read_csv(
filepath_or_buffer='https://raw.githubusercontent.com/aps1070-2019/datasets/master/APS_COVID_Jan22.csv',
index_col=0,
thousands=','
)
from matplotlib import pyplot
display(cases_raw)
df = pd.DataFrame(data=cases_raw)
df.index.tolist() #returns the list of countries
cases_raw.loc['Canada'] #733 cases
Solution 1:[1]
First, let's modify the data to include columns with informative names and also let's use a better tabular representation by moving the dates to rows using .melt:
# Load data and name index as "Country"
df = pd.DataFrame(data=cases_raw).rename_axis("Country").reset_index()
# Move date columns as row values and keep "Count" as value
df = df.melt(id_vars=["Country"], value_vars=df.columns[1:], var_name="Date", value_name="Count")
Our df dataframe looks like this:
Country Date Count
0 Afghanistan 2020-01-22 0
1 Albania 2020-01-22 0
2 Algeria 2020-01-22 0
3 Afghanistan 2020-01-23 0
4 Albania 2020-01-23 0
... ... ... ...
2194 Albania 2022-01-22 246412
2195 Algeria 2022-01-22 234536
2196 Afghanistan 2022-01-23 159649
2197 Albania 2022-01-23 248070
2198 Algeria 2022-01-23 236670
Important: I just used the data from 3 countries to test quickly.
Now, we can group by "Country" and plot each group/country in a subplot by iterating on the axis of a subplot and the groups at the same time (using zip):
# Use nrows and ncols as you prefer, I know that I have 3 countries so...
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12,4), sharey=True)
# Let's create groups by "Country"
country_groups = df.groupby("Country")
# Iterate on group keys (country names) and our subplot axis
for (country_name, ax) in zip(country_groups.groups.keys(), axes.flatten()):
# Plot each group in the plot and include it's title
country_groups.get_group(country_name).plot(ax=ax, title=country_name)
# Display plot
plt.show()
Result:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aaossa |

