Print

38 of 100: Coxcomb chart in matplotlib

At the beginning of the year I challenged myself to create all 100 visualizations using python and matplotlib from the 1 dataset,100 visualizations project and I am sharing with you the code for all the visualizations.

Note: Data Viz Project is copyright Ferdio and available under a Creative Commons Attribution – Non Commercial – No Derivatives 4.0 International license. I asked Ferdio and they told me they used a Design tool to create all the plots.

Collaborate

There are a ton of improvements that can be made on the code, so let me know in the comments any improvements you make and I will update the post accordingly!

To be improved: This viz is missing the curved text. Need to revisit.

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

We will need the following packages:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Generate the data

We could actually go from numpy to matplotlib, but most data projects use pandas to transform the data, so I am using a pandas dataframe as the starting point.

color_dict = {(2004,"Norway"): "#141936", (2022,"Norway"): "#2C324F",
              (2004,"Denmark"): "#973A36", (2022,"Denmark"): "#CC5A43",
              (2004,"Sweden"): "#4562C5", (2022,"Sweden"): "#5475D6",
              }

xy_ticklabel_color,  datalabels_color ='#757C85', "#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)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year, the year labels and then sort the 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)
indexyearcountriessitesyear_lblsub_totaldiffcolor
02004Denmark4’04144.0#973A36
42004Sweden13’042813.0#4562C5
22004Norway5’04135.0#141936
12022Denmark10’22146.0#CC5A43
52022Sweden15’22282.0#5475D6
32022Norway8’22133.0#2C324F

Define the variables

countries = df.countries.unique()
years = df.year.unique()
x = len(df.countries.unique())
codes = df.year_lbl
diff = df['diff']
sites = df.sites
colors = df.color

Plot the chart

fig, ax = plt.subplots(figsize=(5,5),facecolor = "#FFFFFF",subplot_kw=dict(polar=True) )
fig.tight_layout(pad=3.0)

bottom = np.zeros(x)
for year in zip(years,):
    y = df[df["year"] == year]["diff"].values
    x_max = 2*np.pi
    width = x_max/len(countries)
    x_coords = np.linspace(0, x_max, len(countries), endpoint=False)
    #print(x_coords)
    ax.bar(x_coords, y,width= width,bottom = bottom,)
    bottom +=y


for bar, color, site,  in zip(ax.patches, colors, sites, ):
    bar.set_facecolor(color)
    ax.text(
        bar.get_x() + bar.get_width() / 2, 
        bar.get_height()/2+ bar.get_y(),  #height
        site,
         ha='center', va="center", size=8,
        color = datalabels_color, weight= "light",)

angle_offsets = [0.09,0.06,0.10] # Angle between each character
for bar,  country, angle_offset  in zip(ax.patches[3:],  countries, angle_offsets):
    for i, char in enumerate(country):
        #print(np.degrees(bar.get_x()), np.degrees( bar.get_width() / 2))
        angle = bar.get_x() + bar.get_width() /2 - i * angle_offset  # Calculate the angle for each character
        # Rotate each letter so that it curves around the circle
        rotation = np.degrees(angle)  
        ax.text(angle, bar.get_height()+ bar.get_y()+2, char, color = legend_colors, weight= "bold", horizontalalignment='center', verticalalignment='center',
                rotation=rotation, rotation_mode='anchor', fontsize=12)


ax.set_axis_off()
ax.set_theta_zero_location("N")

The result:

38 of 100: Coxcomb chart in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents