Print

79 of 100: Radial bar 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!

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.lines import Line2D
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 = {(2022,"Norway"): "#9194A3", (2004,"Norway"): "#2B314D",
              (2022,"Denmark"): "#E2AFA5", (2004,"Denmark"): "#A54836",
              (2022,"Sweden"): "#C4D6F8", (2004,"Sweden"): "#5375D4",
              }

xy_ticklabel_color, legend_color,  datalabels_color ="#101628", "#757C85", "#FFFFFF"

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
    "sites": [13,15,4,10,5,8]
}

df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year, the totals, the percentage and the degrees for each circle and then sort the data.

df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['total'] = 20  #the circle has been divided by 20 parts
df['pct_group'] = df['sites'] / df.total
df['degrees']= df.pct_group*360

#custom sort
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:5, 2022:4}
df = df.sort_values(by=['countries','year'], key=lambda x: x.map(sort_order_dict))

#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
yearcountriessitessub_totaltotalpct_groupdegreescolor
52022Norway813200.40144.0#9194A3
42004Norway513200.2590.0#2B314D
32022Denmark1014200.50180.0#E2AFA5
22004Denmark414200.2072.0#A54836
12022Sweden1528200.75270.0#C4D6F8
02004Sweden1328200.65234.0#5375D4

Define the variables

x = len(df.countries.unique())
years = df.year.unique()
countries = df.countries.unique()
sites = df.sites
color =df.color

Plot the chart

for i, (country) in enumerate(countries):
    temp_df= df[df.countries == country]
    for dg,site,color in zip(temp_df.degrees, temp_df.sites, temp_df.color):
        angle_range = np.linspace(0, dg)
        theta = [np.deg2rad(a) for a in angle_range]
        r = np.full(len(angle_range), i + 1)  # identical radius values to draw an arc
        line = ax.plot(theta,
            r,
            linewidth=15,
            solid_capstyle="round",
            color=color
            )
        ax.annotate(site, xy= ( theta[-1],r[-1]), color=datalabels_color,ha="center" ,va="center")

#x position in cartesian coordinates
x =[.5]*3
for x,y, country in zip(x,range(1,4), countries):
    r = np.sqrt(x**2 + y**2)
    theta = np.arctan2(y, x)
    ax.text(theta+np.deg2rad(-90),r, country, ha= "right", va="center" )
     
ax.set_rmax(4)
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_axis_off()    

text_legends = ["Before", "After"]
colors = df.color[:2].to_list()
lines = [Line2D([0], [0], color=c, linestyle='-', ) for c in reversed(colors)]
labels  = [f'{text_legend} 2004' for year, text_legend in zip(years, text_legends)]
for year in years:
    plt.figlegend( lines,labels,   
                  labelcolor=xy_ticklabel_color,
            bbox_to_anchor=(0.5, 0), loc="lower center",
                ncols = 2,frameon=False, fontsize= 10)

The result:

79 of 100: Radial bar 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