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
from matplotlib.lines import Line2D
import pandas as pd
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4"}
xy_ticklabel_color, title_color, grid_color, datalabels_color ='#101628',"#101628", "#C8C9C9", "#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['sub_total'] = df.groupby('year')['sites'].transform('sum')
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 | sub_total | color | |
|---|---|---|---|---|---|
| 0 | 2004 | Denmark | 4 | 22 | #A54836 |
| 1 | 2022 | Denmark | 10 | 33 | #A54836 |
| 2 | 2004 | Norway | 5 | 22 | #2B314D |
| 3 | 2022 | Norway | 8 | 33 | #2B314D |
| 4 | 2004 | Sweden | 13 | 22 | #5375D4 |
| 5 | 2022 | Sweden | 15 | 33 | #5375D4 |
titles = ["World Heritage Sites\n in 2004","World Heritage Sites\n in 2022"]
fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1,figsize=(5,5), facecolor = "#FFFFFF")
for (year, group),title, ax in zip(df.groupby("year"), titles, axes.ravel()):
patches, texts, autotexts = ax.pie(
group.sites,
labels = group.sites,
autopct='%1.0f%%',
startangle=90,
colors= group.color)
ax.set_xlabel(
group.sub_total.iloc[0],
color = title_color,
size = 14,
weight= "bold",
labelpad = 23
)
ax.set_title(
title,
size=10,
x=0.5,
y=1.2,
color= title_color
)
[autotext.set_color('white') for autotext in autotexts]
#add legend
lines = [Line2D([0], [0], color=c, marker='o',linestyle='', markersize=10,) for c in df.color.unique()]
fig.legend(
lines,
df.countries.unique().tolist(),
labelcolor= title_color,
bbox_to_anchor= (0.5, -0),
loc = "lower center",
ncols = 3,
frameon = False,
fontsize = 8
)
fig