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
from matplotlib.lines import Line2D
color_dict = {2004: "#2B314D", 2022: "#A54836" }
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE" }
xy_ticklabel_color, grand_totals_color, grid_color, datalabels_color ='#9BA0A6',"#101628", "#E9ECED", "#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['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['ctry_code'] = df.countries.map(code_dict)
#custom sort
sort_order_dict = {"Denmark":1, "Sweden":3, "Norway":2, }
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.year.map(color_dict)
df
| year | countries | sites | sub_total | ctry_code | color | |
|---|---|---|---|---|---|---|
| 0 | 2004 | Denmark | 4 | 14 | DK | #2B314D |
| 1 | 2022 | Denmark | 10 | 14 | DK | #A54836 |
| 2 | 2004 | Norway | 5 | 13 | NO | #2B314D |
| 3 | 2022 | Norway | 8 | 13 | NO | #A54836 |
| 4 | 2004 | Sweden | 13 | 28 | SE | #2B314D |
| 5 | 2022 | Sweden | 15 | 28 | SE | #A54836 |
fig, ax = plt.subplots( figsize=(6,5),facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=6.0)
for country, group1 in df.groupby("countries"):
ax.plot(
group1.ctry_code,
group1.sites,
"-",
color = group1.color.iloc[0])
for year, group2 in df.groupby("year"):
ax.plot(
group2.ctry_code,
group2.sites,
"o",
ms=12,
mec= "w",
color= group2.color.iloc[0]
)
fig
ax.tick_params(
axis='both',
which='major',
length=0,
labelsize=10,
colors = xy_ticklabel_color
)
ax.grid(color = grid_color)
ax.set(xlim = (-1,3), ylim = (0,20))
ax.yaxis.set_ticks(np.arange(0, 25, 5), labels = [0,5,10,15,20])
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_color(grid_color)
ax.spines[axis].set_zorder(0)
lines = [Line2D([0], [0], color=c, marker='o',linestyle='', markersize=10,) for c in df.color.unique()]
fig.legend(
lines,
df.year.unique(),
bbox_to_anchor=(0.5, -0.02),
loc="lower center",
ncols = 2,
frameon=False,
fontsize= 12
)
fig