Udit Vashisht
Author: Udit Vashisht


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

  • 5 minutes read
  • 483 Views
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.

# piechart_in_matplotlib.py

import matplotlib.pyplot as plt

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

matplotlib_tutorial_pie_chart.png

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

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

# piechart_in_matplotlib.py

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.

# piechart_in_matplotlib.py

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

matplotlib_tutorial_piechart.png

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.

# piechart_in_matplotlib.py

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")
plt.show()

matplotlib_tutorial_piechart_.png

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.

# piechart_in_matplotlib.py

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")
plt.show()

matplotlib_tutorial_piechart__.png

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.

# piechart_in_matplotlib.py

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

matplotlib_tutorial_piechart_clockwise.png

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.

# piechart_in_matplotlib.py

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")
plt.show()

matplotlib_tutorial_piechart_explode.png

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

# piechart_in_matplotlib.py

plt.pie(total_population, labels=ages, explode=explode,
        shadow=True,
        autopct='%1.1f%%',
        wedgeprops={'edgecolor': 'black'})

matplotlib_tutorial_piechart_shadow.png

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

Python Tutorial for Beginners
By Udit Vashisht

Python Tutorial for Beginners

Have you heard a lot about Python Language? Are you looking for free and reliable resource to learn Python? If Yes, your search for the Best Python Tutorial is over.

We are excited to bring an exhaustive Python tutorial for a complete beginner. Even ...

Read More
Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10
By Udit Vashisht

Matplotlib Subplot in Python | Chapter 10

In this Matplotlib Subplot tutorial, we will be learning to create Matplotlib Subplots. Till now, we have been using matplotlib.pyplot() to create the plots. But now, we will be using matplotlib.pyplot.subplots() (ptl.subplots()) to create Matplotlib Subplots.

Matplotlib.pyplot() or plt was automatically ...

Read More
Plot Time Series in Python | Matplotlib Tutorial | Chapter 8
By Udit Vashisht

Plot Time Series data in Python using Matplotlib

In this tutorial we will learn to create a scatter plot of time series data in Python using matplotlib.pyplot.plot_date(). We will use Pandas Dataframe to extract the time series data from a CSV file using pandas.read_csv().

The ...

Read More

Search
Tags
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 remove.bg 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