Generate the data and import packagesΒΆ
First, we need to create the data. I'll start by defining it as a dictionary and then convert it into a pandas DataFrame, since pandas is commonly used in many projects for data manipulation.
# tutorial
import matplotlib.pyplot as plt
import pandas as pd
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4"}
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE"}
(
xy_ticklabel_color,
xy_label_color,
) = (
"#101628",
"#101628",
)
data = {
"year": [2004, 2022, 2004, 2022, 2004, 2022],
"countries": ["Denmark", "Denmark", "Norway", "Norway", "Sweden", "Sweden"],
"sites": [4, 10, 5, 8, 13, 15],
}
df = pd.DataFrame(data)
df["ctry_code"] = df.countries.map(code_dict)
df = df.sort_values(["countries"], ascending=True).reset_index(drop=True)
# map the colors of a dict to a dataframe
df["color"] = df.countries.map(color_dict)
df
| year | countries | sites | ctry_code | color | |
|---|---|---|---|---|---|
| 0 | 2004 | Denmark | 4 | DK | #A54836 |
| 1 | 2022 | Denmark | 10 | DK | #A54836 |
| 2 | 2004 | Norway | 5 | NO | #2B314D |
| 3 | 2022 | Norway | 8 | NO | #2B314D |
| 4 | 2004 | Sweden | 13 | SE | #5375D4 |
| 5 | 2022 | Sweden | 15 | SE | #5375D4 |
groups = df.groupby("year")
groups
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001A57A490680>
fig, axes = plt.subplots( ncols=df.year.nunique(), nrows=1, figsize=(6, 5), sharex=True, sharey=True, facecolor="#FFFFFF", zorder=1 )
fig.tight_layout(pad=6.0)
for (year,group), ax in zip(groups, axes.ravel()):
for row in group.itertuples():
site = row.sites
ax.plot(
[row.ctry_code] * site,
list(range(site)),
"o",
ms = 10,
linestyle = "",
color = row.color,
clip_on = False
)
#add labels
ax.set_xlabel(
year,
color = xy_label_color,
size = 14,
weight = "bold",
labelpad = 23
)
#styling
ax.tick_params(
axis = "both",
which = "both",
labelsize = 12,
length = 0,
color = xy_ticklabel_color,
pad = 13,
labelleft = False
),
ax.set_frame_on(False)