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.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4"}
xy_ticklabel_color, grid_color = "#757C85", "#C8C9C9"
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("countries")["sites"].transform("sum")
df = df.sort_values(["sub_total"], ascending=False).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 | Sweden | 13 | 28 | #5375D4 |
| 1 | 2022 | Sweden | 15 | 28 | #5375D4 |
| 2 | 2022 | Denmark | 10 | 14 | #A54836 |
| 3 | 2004 | Denmark | 4 | 14 | #A54836 |
| 4 | 2022 | Norway | 8 | 13 | #2B314D |
| 5 | 2004 | Norway | 5 | 13 | #2B314D |
groups = df.groupby("countries", sort = False)
year_max = df.year.max()
years = df.year.unique()
fig, ax = plt.subplots(figsize=(5, 5), facecolor="#FFFFFF")
for countries, group in groups:
x = group.year
y = group.sites
color = group.color.iloc[0]
ax.plot(
x,
y,
color = color
)
ax.fill_between(
x,
y,
color = color
)
if (x == year_max).any():
ax.text(
year_max + 1,
y.iloc[0],
group.countries.iloc[0],
ha = "left",
va = "center",
color = color,
clip_on = False,
)
add some styling:
#set the ticks and labels
ax.tick_params(
axis = "both",
which = "major",
length = 0,
labelsize = 12,
colors = xy_ticklabel_color,
pad = 5
)
ax.yaxis.set_ticks(np.arange(0, 20, 5), labels=[0, 5, 10, 15])
ax.xaxis.set_ticks(years, labels=years)
major_ticks = np.arange(0, 16, 1)
ax.set_xlim([df.year.min(), year_max])
ax.set_yticks(major_ticks)
ax.grid(
which = "major",
axis = "y",
linestyle = "-",
alpha = 0.4,
color = grid_color
)
ax.set_frame_on(False)
fig