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 numpy as np
import pandas as pd
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4"}
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE"}
xy_ticklabel_color, grand_totals_color, grid_color, datalabels_color = (
"#757C85",
"#101628",
"#C8C9C9",
"#FFFFFF",
)
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", "year"], 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")
fig, axes = plt.subplots(nrows=df.year.nunique(), ncols=1, figsize=(5, 5), facecolor="#FFFFFF")
for (year, group), ax in zip(groups, axes.ravel()):
patches, texts, autotexts = ax.pie(
group.sites,
labels=group.ctry_code,
autopct="%1.0f%%",
pctdistance=0.65,
wedgeprops=dict(width=0.65),
startangle=90,
colors=group.color,
)
# add year labels
ax.text(
0.5,
0.5,
year,
va="center",
ha="center",
transform=ax.transAxes,
size=8,
)
# add wedges labels
for autotext in autotexts:
autotext.set_color("white")
autotext.set_fontsize(8)