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 pandas as pd
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4"}
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE"}
(xy_ticklabel_color,) = ("#757C85",)
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["year_lbl"] = "'" + df["year"].astype(str).str[-2:].astype(str)
df["sub_total"] = df.groupby("countries")["sites"].transform("sum")
df["ctry_code"] = df.countries.map(code_dict)
df = df.sort_values(["sites"], ascending=True).reset_index(drop=True)
df["color"] = df.countries.map(color_dict)
df
| year | countries | sites | year_lbl | sub_total | ctry_code | color | |
|---|---|---|---|---|---|---|---|
| 0 | 2004 | Denmark | 4 | '04 | 14 | DK | #A54836 |
| 1 | 2004 | Norway | 5 | '04 | 13 | NO | #2B314D |
| 2 | 2022 | Norway | 8 | '22 | 13 | NO | #2B314D |
| 3 | 2022 | Denmark | 10 | '22 | 14 | DK | #A54836 |
| 4 | 2004 | Sweden | 13 | '04 | 28 | SE | #5375D4 |
| 5 | 2022 | Sweden | 15 | '22 | 28 | SE | #5375D4 |
sites = df.sites
colors = df.color
codes = df.ctry_code
tick_labels = [f' {code}\n{lbl}' for code, lbl in zip(codes, df.year_lbl) ]
tick_labels
[" DK\n'04", " NO\n'04", " NO\n'22", " DK\n'22", " SE\n'04", " SE\n'22"]
fig, ax = plt.subplots(figsize=(7, 5), facecolor="w")
fig.tight_layout(pad=3.0)
ax.bar(
df.index,
height = sites,
color = colors,
label = codes
)
<BarContainer object of 6 artists>
for bar, site in zip(ax.patches, sites):
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + bar.get_y(), # height
site,
ha = "center",
va = "bottom",
color = xy_ticklabel_color,
size = 12,
weight = "light",
)
fig
ax.xaxis.set_ticks(range(6), labels=tick_labels)
for xtick, color in zip(ax.get_xticklabels(), colors):
xtick.set_color(color)
ax.tick_params(
axis="both",
which="both",
length=0,
pad=10,
labelleft = False,
)
ax.set_frame_on(False)
fig