DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

  • 5 minutes read
Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

    Table of Contents

Matplotlib Tutorial in Python

Chapter 3 | Creating Pie Charts in Python

In this chapter, we will learn to create Pie Charts in Matplotlib in Python. Pie Charts are an intiutive way of showing data, wherein each category is shown as a portion of the pie. Let us get started.

Matplotlib Tutorials in Python | Creating a simple Pie Chart in Matplotlib

In Pie Chart data is shown as slices for each category. A pie chart is plotted using plt.pie() method.


import matplotlib.pyplot as plt

slices = [70, 30]
plt.title("A Simple Pie Chart")


Matplotlib Tutorials in Python - Adding labels and edges to Pie Chart

We can add labels to our pie chart using the following code :-


labels = ['seventy', 'thirty']
plt.pie(slices, labels = labels)

If we want to add edges to each portion/slice of the pie we will be passing wedgeprops as an argument to plt.pie() which takes a dictionary with keys like edgecolor, linewidth etc. and their values.


slices = [70, 30]
labels = ['Seventy', 'Thirty']
plt.pie(slices, labels = labels, wedgeprops={'edgecolor' :'blue'})


Matplotlib Tutorials in Python - Adding custom colors to the Pie Chart in Matplotlib

Instead of using automatic colors, you can also use customs colors for the data in your Matplotlib Pie Chart. For that, you will have to pass a list of custom colors (having as many colors as items) to plt.pie() method. Instead of common color names, you can also pass hex values to Matplotlib Pie Chart.


import matplotlib.pyplot as plt

slices = [70, 30, 20, 40]
labels = ['Seventy', 'Thirty', 'Other', 'Another']
colors = ['red', 'yellow', 'blue', 'green']
plt.pie(slices, labels=labels, wedgeprops={'edgecolor': 'black'})
plt.title("A Simple Pie Chart")


Matplotlib Tutorials in Python - Creating Pie Chart of Population Data

In chapter 1 and chapter 2 we plotted total population of India for ages 12 to 21. Now, we will be using that data to plot Python Pie Chart.


import matplotlib.pyplot as plt

ages = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

total_population = [27877307, 24280683, 25258169, 25899454, 24592293, 21217467, 27958147, 20859088, 28882735, 19978972]

plt.pie(total_population, labels=ages, wedgeprops={'edgecolor': 'black'})
plt.title("A Simple Pie Chart")


Since, our data is uniformly distribued i.e. each age group has almost similar population, this pie chart looks a bit descriptive. However, a pie-chart is suitable only to analyse 3-5 items.

In the above chart, you might have noticed that the values/items are moving in counter-clockwise direction from 12 to 21. If for some reason, you want to move it in clockwise direction. You have to set counterclock parameter of plt.pie() as False.You can check rest of the parameters here.


plt.pie(total_population, labels=ages, wedgeprops={'edgecolor': 'black'}, counterclock=False)


Making certain slice of Pie Chart explode in Matplotlib

If you want to put emphasise on certain slice and want it to look different or look-out of the whole data, you can pass explode argument to the plt.pie(), which takes a list of floats, where each item represents the fraction of radius by which you want your slice to move away from the center. 0 means no explode and 0.1 will mean the slice will move away from the centre by 10% of the radius.


import matplotlib.pyplot as plt

ages = [17, 18, 19, 20, 21]

total_population = [21217467, 27958147, 20859088, 28882735, 19978972]
explode = [0, 0, 0, 0, 0.1]

plt.pie(total_population, labels=ages, explode=explode, wedgeprops={'edgecolor': 'black'})
plt.title("A Simple Pie Chart")


In the above chart we wanted to make age 21 stand-out so we have set its corresponding values as 0.1 in explode and then passed explode as explode list in plt.pie().

Matplotlib Tutorials in Python - Customizing the Pie Chart

You can add shadow to the Pie Chart by using shadow = True, also we can add percentage to our pie chart


plt.pie(total_population, labels=ages, explode=explode,
        wedgeprops={'edgecolor': 'black'})


Video Tutorial

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.

In the next chapter we will learn about drawing Stack Plots in Python

Related Posts

Chapter 3 - Executing a Python Script
By Udit Vashisht

How to run a Python script?

In our previous chapter, we have strongly recommended you to ditch IDLE and use some code-editor and terminal(MacOS/Linux) or Powershell(Windows) to write and execute your python script. In this chapter we will tell you how to do that.

First and foremost for the ...

Read More
What is a Python List?
By Udit Vashisht

What is a Python List?

A Python List is the most common and versatile data structure in Python. It is one of the six built-in types of sequences in Python language. Each item in a Python list is separated by comma (,) and are enclosed in square brackets ([]). It ...

Read More
How to fill area between the Line Plots? | Matplotlib Tutorial in Python | Chapter 5
By Udit Vashisht

How to fill area between the line plots in Matplotlib?

You can easily fill the area with any color between the lines or under a curve in Matplotlib Line Plots using plt.fill_between().

Parameters of matplotlib.pyplot.fill_between() or plt.fill_between()

The syntax for plt.fill_between() is :

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, ...

Read More
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python