Print

45 of 100: Proportional Area chart circular 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: Need to automate the axes, colors, lables and angles.

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
from matplotlib.patches import Wedge
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"): "#9194A3", (2022,"Norway"): "#2B314D",
              (2004,"Denmark"): "#E2AFA5", (2022,"Denmark"): "#A54836",
              (2004,"Sweden"): "#C4D6F8", (2022,"Sweden"): "#5375D4",
              }

xy_ticklabel_color, xlabel_color,  grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#FFFFFF"

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : ["Norway", "Norway","Sweden", "Sweden",  "Denmark", "Denmark",],
    "sites": [5,8,13,15,4,10,]
}
df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to sort the data.

df = df.sort_values(['year' ], ascending=False ).reset_index(drop=True)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
yearcountriessitesctry_codecolor
02022Norway8NO#2B314D
12022Sweden15SW#5375D4
22022Denmark10DE#A54836
32004Norway5NO#9194A3
42004Sweden13SW#C4D6F8
52004Denmark4DE#E2AFA5

Define the variables

Calculate the centers and the position of the y-lables:

offset = 6
sites2022 = df[df.year == df.year.max()]['sites'].to_numpy()
mid_circle = np.divide(sites2022,2)

cum_sum = np.cumsum(sites2022)
center_circle = np.subtract(cum_sum,mid_circle)

centers = [(0,center_circle + offset*(i+1)) for i,center_circle in enumerate(center_circle)]*2
label_y =  [center_circle + offset*(i+1) for i,center_circle in enumerate(center_circle)]*2
label_y

Add the rest of the variables:

sites =df.sites
codes = df.ctry_code
colors = df.color
countries = df.countries.unique()

theta1 = [-90]*len(countries)+[90]*len(countries)
theta2 = [90]*len(countries)+[-90]*len(countries)

radius = df.sites/2
label_x = [10]*len(countries)+[-10]*len(countries)

Plot the chart


fig, ax = plt.subplots( figsize=(10,5), facecolor = "#FFFFFF")
ax.set_aspect('equal')

for radie,  site, color,lb_x,lb_y, center, th1, th2 in zip(radius,sites, colors, label_x,label_y, centers, theta1, theta2):
    patches = Wedge(center, radie, th1, th2, color=color, )
    ax.add_patch(patches)
    ax.annotate(site, xy=(lb_x-0.6, lb_y ),  fontsize=10, color = xy_ticklabel_color,) 

ax.set_xlim([-15, 15])
ax.set_ylim([0, 58])
ax.axvline(x=0,ymin=-4,ymax=17, color =grid_color,lw=0.5,snap=False)
ax.tick_params(length=0)

ax.set_xticklabels([])
ax.set_yticklabels([])       
ax.set_frame_on(False)

#add datalabels
for center, code in zip(centers[:3],codes) :
    ax.annotate(code, xy= center, va="center",ha= "center", weight="bold", color = datalabels_color)

ax.text(0.1, 1, df.year.min(), size= 12, ha="left", transform = ax.transAxes, color= xlabel_color)
ax.text(1, 1, df.year.max(), size = 12, ha="right",  transform = ax.transAxes, color= xlabel_color)

The result:

45 of 100: Proportional Area chart circular in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

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

Table of Contents