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 = {
(2004, "Norway"): "#141936",
(2022, "Norway"): "#2C324F",
(2004, "Denmark"): "#973A36",
(2022, "Denmark"): "#CC5A43",
(2004, "Sweden"): "#4562C5",
(2022, "Sweden"): "#5475D6",
}
xy_ticklabel_color, legend_colors, datalabels_color = "#757C85", "#6C747D", "#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["year_lbl"] = "'" + df["year"].astype(str).str[-2:].astype(str)
df["sub_total"] = df.groupby("countries")["sites"].transform("sum")
sort_order_dict = {
"Denmark": 1,
"Sweden": 2,
"Norway": 3,
2022: 5,
2004: 4,
}
df = df.sort_values(
by=[
"year",
"countries",
],
key=lambda x: x.map(sort_order_dict),
)
df["diff"] = df.groupby(["countries"])["sites"].diff()
df["diff"].fillna(df.sites, inplace=True)
# Add the color based on the color dictionary
df["color"] = df.set_index(["year", "countries"]).index.map(color_dict.get)
df
C:\Users\Ruth Pozuelo\AppData\Local\Temp\ipykernel_13324\4073035565.py:41: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
df["diff"].fillna(df.sites, inplace=True)
| year | countries | sites | year_lbl | sub_total | diff | color | |
|---|---|---|---|---|---|---|---|
| 0 | 2004 | Denmark | 4 | '04 | 14 | 4.0 | #973A36 |
| 4 | 2004 | Sweden | 13 | '04 | 28 | 13.0 | #4562C5 |
| 2 | 2004 | Norway | 5 | '04 | 13 | 5.0 | #141936 |
| 1 | 2022 | Denmark | 10 | '22 | 14 | 6.0 | #CC5A43 |
| 5 | 2022 | Sweden | 15 | '22 | 28 | 2.0 | #5475D6 |
| 3 | 2022 | Norway | 8 | '22 | 13 | 3.0 | #2C324F |
groups = df.groupby("year", sort = False)["diff"].apply(np.array)
countries = df.countries.unique()
cnt_countries = len(countries)
fig, ax = plt.subplots(figsize=(5, 5), facecolor="#FFFFFF", subplot_kw=dict(polar=True))
fig.tight_layout(pad=3.0)
ax.set_axis_off()
ax.set_theta_zero_location("N")
bottom = np.zeros(cnt_countries)
for year, sites in groups.items():
x = np.linspace(0, 2 * np.pi, cnt_countries, endpoint = False) #calculat the angles
ax.bar(
x,
sites,
width=(2 * np.pi)/cnt_countries,
bottom=bottom,
)
bottom += sites
Add the labels and colors to the bars¶
for bar, row in zip(ax.patches,df.itertuples()):
bar.set_facecolor(row.color)
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() / 2 + bar.get_y(), # height
row.sites,
ha="center",
va="center",
size=8,
color=datalabels_color,
weight="light",
)
fig
Add curved text¶
angle_offsets = [0.07, 0.045, 0.08] #space between letters
for bar, country, angle_offset in zip(ax.patches[3:], countries, angle_offsets):
for i, char in enumerate(country):
angle = ( bar.get_x() + bar.get_width() / 2 - i * angle_offset ) # Calculate the angle for each character
rotation = np.degrees(angle)
ax.text(
angle,
bar.get_height() + bar.get_y() + 2,
char,
fontsize=8,
color=legend_colors,
weight="light",
horizontalalignment="center",
va="center",
rotation=rotation,
rotation_mode="anchor",
)
fig