Creating Pie Charts in Matplotlib

I tend to think that pie charts should be avoided in 99% of the cases that they are used in. Unless your goal is to mislead (which is sometimes the case!), or you have a strict use case for them, you can normally find a better way to communicate your point.

That being said, just because we won’t do something, doesn’t mean we don’t need to know how it is done. As such, this article is going to take us through a simple example of creating a pie chart in Matplotlib.

As ever, let’s get our modules and data ready to go.

In [1]:
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

Our pie chart is going to display the share of Premier League wins, as shown in our data below:

In [2]:
leagueWins = {'Team':['Manchester United','Blackburn Rovers','Arsenal',
                     'Chelsea','Manchester City','Leicester City'],
             'Championships':[13,1,3,4,2,1]}

df = pd.DataFrame(leagueWins, columns=['Team','Championships'])
df
Out[2]:
Team Championships
0 Manchester United 13
1 Blackburn Rovers 1
2 Arsenal 3
3 Chelsea 4
4 Manchester City 2
5 Leicester City 1

So we want the pie chart to plot the numbers in our Championships column. ‘plt.pie()’ will do exactly that:

In [3]:
plt.pie(df['Championships'])

#This next line just makes the plot look a little cleaner in this notebook
plt.tight_layout()

So we have a pie chart! It doesn’t tell us a great deal without labels, except that there is a big blue lump that takes up over half of the pie.

As with all of its other plot types, Matplotlib gives good customisation options. Let’s use some of these to add a title, labels and colours in our arguments:

In [4]:
#Create a list of the colours used for the teams, in order.
teamColours=['#f40206','#0560b5','#ce0000','#1125ff','#28cdff','#091ebc']

plt.pie(df['Championships'],
        #Data labels are the team names in the dataFrame
       labels = df['Team'],
        #Assign our colours list
       colors = teamColours,
        #Give a tidier angle to ur first data angle
        startangle = 90
       )

#Add a title
plt.title("Premier League Titles")
plt.tight_layout()

Summary

I strongly recommend not using pie charts, we just struggle to process circular space in comparison to bar charts or even a table – especially when the numbers are relatively simple.

However, just in case it is ever needed, we have seen in this article how easy it is to create a pie chart in Matplotlib with the ‘.pie()’ command. It is also clear that we need to make use of Matplotlib’s customisation features to tidy things up, add a bit of relevant colour and titles. Passing these as arguments into the earlier command makes this easy.

Next up, read up on some different (better!) visualisation types!