Matplotlib Pie Chart Tutorial

In this Python Matplotlib tutorial, we will discuss the Matplotlib pie chart in matplotlib. Here we will cover different examples related to the pie chart using matplotlib. And we will also cover the following topics:

  • Matplotlib pie chart in python
  • Matplotlib pie chart example
  • Matplotlib pie chart title
  • Matplotlib pie chart title position
  • Matplotlib pie chart title font size
  • Matplotlib pie chart colors
  • Matplotlib pie chart with labels
  • Matplotlib pie chart background color
  • Matplotlib pie chart hex color
  • Matplotlib pie chart with legend
  • Matplotlib pie chart label fontsize
  • Matplotlib pie chart legend fontsize
  • Matplotlib pie chart autopct
  • Matplotlib pie chart autopct position
  • Matplotlib pie chart wedgeprops
  • Matplotlib pie chart edge color
  • Matplotlib pie chart increase size
  • Matplotlib pie chart labels inside
  • Matplotlib pie chart bold text
  • Matplotlib pie chart bigger
  • Matplotlib pie chart textprops
  • Matplotlib pie chart text color
  • Matplotlib pie chart hatch
  • Matplotlib pie chart alpha
  • Matplotlib pie chart explode
  • Matplotlib pie chart shadow
  • Matplotlib pie chart frame
  • Numpy matplotlib pie chart
  • Matplotlib pie chart label header
  • Matplotlib multiple pie chart
  • Matplotlib pie chart move legend
  • Matplotlib pie chart move labels
  • Matplotlib pie chart not circle
  • Matplotlib pie chart side by side
  • Matplotlib pie chart save
  • Matplotlib pie chart turn off labels
  • Matplotlib pie chart from dataframe
  • Matplotlib nested pie chart with labels
  • Matplotlib pie chart remove labels
  • Matplotlib pie chart radius
  • Matplotlib pie chart rotate labels
  • Matplotlib pie chart subplots
  • Matplotlib pie chart start angle
  • Matplotlib pie chart dictionary
  • Matplotlib half pie chart
  • Matplotlib pie chart absolute value
  • Matplotlib pie chart donut
  • Matplotlib pie chart annotation
  • Matplotlib pie chart categorical data

Table of Contents

Matplotlib pie chart in python

In this section, we’ll learn what is pie chart and how to create a pie chart. Also how to use the python matplotlib tool to create a pie chart to represent your data. Before starting the topic, firstly we have to understand what does pie chart means:

A pie chart is a special type of chart that uses a circular graph to represent the data. It is one of the most often used graphs for representing data that uses the attributes of circles, spheres, and angular data to represent real-world data.

  • The pie chart is used to display only one series of data.
  • The whole circular plot represents the whole data and the slices represent the data sets.
  • The slices of the Pie are known as wedges.
  • The area of the complete pie chart is equal to the total percentage of the given data.
  • The area of the slices is equal to the percentage of the parts of the data.

In matplotlib, the pie() function is used to create a pie chart. The syntax is given below:

matplotlib.pyplot.pie(x, explode=None, labels=None, 
                      colors=None, autopct=None, 
                      pctdistance=0.6, shadow=False, 
                      labeldistance=1.1, startangle=None, 
                      radius=None, counterclock=True, 
                      wedgeprops=None, textprops=None, 
                      center=(0,0), frame=False, 
                      rotatelabels=False, * , data=None)
 

The following are the parameters:

ParameterValueDescription
xarraySpecify the sizes of wedges.
explodearray
Default: None
If not None is a len(x) array that indicates the fraction of the radius by which each wedge should be shifted.
labellist
Default: None
The labels for each wedge are specified by a string sequence.
colorsarray
Default: None
The pie chart will cycle through a sequence of matplotlib color args. If none, the colors from the currently active cycle will be used.
autopctstring or function
Default: None
If not None, a string or function is used to label the wedges with their numerical value. Inside the wedge, the labels will be placed. The label will be fmt% pct if it is a format string. It will be invoked if it is a function.
pctdistancefloat
Default:0.6
The distance between the center of each pie slice and the beginning of the autopct-generated text. If autopct is None, it is ignored.
shadowbool
Default: False
Just below the pie, draw a shadow.
normalizebool
Default: False
Always create a full pie when True by normalising x to sum(x) == 1. If sum(x) = 1, False creates a partial pie, and if sum(x) > 1, it raises a ValueError.
labeldistancefloat or None
Default: 1.1
The pie labels are drawn at a radial distance. If None is selected, no labels are drawn, but they are saved for use in the legend ().
startanglefloat
Default: 0 degrees
The counterclockwise angle at which the pie’s beginning is rotated from the x-axis.
radiusfloat
Default: 1
Specify the radius of the pie.
counterclockbool
Default: True
Specify whether the fractions should be rotated clockwise or counterclockwise.
wedgepropsdict
Default: None
The pie is made up of a dict of arguments provided to the wedge objects that make up the pie. For example, wedgeprops =’ linewidth’: 3 can be used to set the width of the wedge border lines to 3.
textpropsdict
Default: None
Arguments to pass to the text objects in a dict.
center(float,float)
Default: (0,0)
The coordinates of the chart’s center.
framebool
Default: False
If true, plot the Axes frame with the chart.
rotatelabelsbool
Default: False
If true, rotate each label to the angle of the corresponding slice.
dataindexable objectThe following parameters take a string s, which is interpreted as data[s] if given (unless an exception is raised):
x, explode, labels, colors

Also, check: Matplotlib default figure size

Matplotlib pie chart example

Here, we will discuss an example related to the Matplotlib pie chart.

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates


data = [20, 16, 8, 9.8] 

# Plot

plt.pie(data) 

# Display

plt.show() 
  • First, import matplotlib.pyplot library for data visualization.
  • Next, define the data coordinates used for plotting.
  • To create a pie chart, we use the pie() function.
  • To display the graph, use the show() function.

Output:

matplotlib pie chart example
plt.pie()

Check: Matplotlib savefig blank image

Matplotlib pie chart title

Here, we’ll learn to add a title to the pie chart. To add a title we use the title() method of the matplotlib pyplot module.

The following is the syntax to add a title:

matplotlib.pyplot.title()

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates


subjects= ['English', 'Hindi', 'Science', 'Maths']

like = [18, 9, 16, 7]

# Plot

plt.pie(like, labels=subjects) 

# Title

plt.title('Subject like by students')

# Display

plt.show() 
  • Here we define data coordinates and labels.
  • Next, we use the pie() function to create a pie chart.
  • To add a title to the pie chart, use the title() function.
matplotlib pie chart title
plt.title()

Read: Matplotlib save as png

Matplotlib pie chart title position

Here we’ll see an example of a pie chart with a title at different positions.

The required syntax is:

matplotlib.pyplot.pie(label, loc= 'center' | 'left' | 'right' )

Example:

# Import Library


import matplotlib.pyplot as plt

# Define Data Coordinates


age_group = ['Infancy', 'Childhood', 'Adolescence', 
             'Adulthood', 'Old Age']

persons = [10, 15, 25, 50, 35]

# Plot

plt.pie(persons, labels=age_group) 

# Title

plt.title('Survey',loc='right',color='r')

                #OR

plt.title('Survey',loc='left',color='r')

# Display

plt.show() 

Here we pass loc as a parameter to title() function and set its value to right and left.

Matplotlib pie chart title position
plt.title(loc=’right’)
matplotlib pie chart title with position
plt.left(loc=’left’)

Read: Matplotlib bar chart labels

Matplotlib pie chart title font size

Here we’ll see an example of a pie chart with a title and here we also change the fontsize of the title.

The following is the syntax:

matplotlib.pyplot.title(label, fontsize=None)

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

pet = ['Dog', 'Cat', 'Rabbit', 'Parrot', 'Fish']
 
owner = [50, 15, 8, 20, 12]

# Plot

plt.pie(owner, labels=pet) 

# Title fontsize

plt.title('Pet Ownership',fontsize=20)

# Display

plt.show() 

Here we pass the fontsize argument to the title() function to change the size of the title font.

Output:

matplotlib pie chart title font size
plt.title(fontsize=None)

Read: Matplotlib plot error bars

Matplotlib pie chart colors

Here we’ll see an example, where we’ll change the color of the pie chart in matplotlib. To change the color of the pie chart, we’ll pass an array of colors to the colors argument.

The following is the syntax:

matplotlib.pyplot.pie(x, labels=None, colors=None)

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

movie = ['Comedy','Drama','Action']
 
popularity = [60, 40, 25]

# Colors

pie_colors = ['tab:orange', 'tab:cyan', 'tab:gray']

# Plot

plt.pie(popularity, labels=movie, colors=pie_colors) 

# Display

plt.show() 
  • In the above example, firstly we import matplotlib.pyplot library.
  • After this, we define data coordinates and labels used for plotting.
  • Next, we create a list of colors.
  • To plot the pie chart with colors of your choice, we use the pie() method with the colors argument.
matplotlib pie chart colors
plt.pie(colors=None)

Read: Matplotlib scatter marker

Matplotlib pie chart with labels

To create a pie chart with labels, we’ll need to pass a labels argument to the pie() method.

The following is the syntax:

matplotlib.pyplot.pie(x, labels=None)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

icecream = ['Chocolate','Vanilla','Straberry']

# Labels
 
popularity = [55, 30, 15]

# Plot

plt.pie(popularity, labels=icecream) 

# Display

plt.show() 
  • Here we define data for plotting and labels also.
  • To plot a pie chart, we use the pie() method.
  • To add labels, we pass the labels argument.
matplotlib pie chart with labels
plt.pie(labels=None)

Read: Matplotlib change background color

Matplotlib pie chart background color

To set a background color of the pie chart we use the figure() method with facecolor argument.

The syntax is as fellow:

matplotlib.pyplot.figure(facecolor=None)

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

emojis = ['Happy Face', 'Sad Face', 'Hearts', 'Hand Gestures', 
          'Others']
 
popularity = [45, 14, 13, 7, 21]

# Background Color

plt.figure(facecolor='salmon')

# Plot

plt.pie(popularity, labels=emojis) 

# Display

plt.show() 

Here we create a pie chart that represents the most used emojis, by using the pie() method. And to change the background color of an image we use the figure() function with the facecolor argument.

matplotlib pie chart background color
plt.figure(facecolor=None)

Read: Matplotlib 3D scatter

Matplotlib pie chart hex color

Here we’ll create a pie chart and set the color of slices using hex colors. To get a good-looking chart we preferably select light shades.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates and labels

languages = ['Python', 'Ruby', 'Java', 'Php']
 
popularity = [40, 20, 10, 30]

# Add colors

colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']

# Plot

plt.pie(popularity, labels=languages, colors=colors) 

# Display

plt.show() 

Here we set colors of slices using hex colors code. To change the colors we use the colors argument.

matplotlib pie chart hex color
Hex Color

Read: Stacked Bar Chart Matplotlib

Matplotlib pie chart with legend

Here we’ll see an example of a pie chart with legend. To add a legend to a plot, we use the legend() function of the pyplot module of matplotlib.

The following is the syntax:

matplotlib.pyplot.legend(labels, loc=None)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

diet = ['Fruit', 'Protein', 'Vegetables', 'Dairy', 'Grains', 
        'Other']
 
quantity = [30, 23, 18, 15, 9, 5]

# Plot

plt.pie(quantity)

# Add legend

plt.legend(labels=diet, loc='upper center', 
           bbox_to_anchor=(0.5, -0.04), ncol=2)

# Display

plt.show() 
  • Import the pyplot function of the matplotlib library.
  • Define data to be plotted.
  • Next, define an array of labels also.
  • To plot a pie chart, use the pie() function.
  • To add a legend, use the legend() function.
matplotlib pie chart with legend
plt.legend()

Read: Draw vertical line matplotlib

Matplotlib pie chart label fontsize

Here we’ll see an example of a pie chart where we are going to change the fontsize of the labels. To change the fontsize we use the textprops argument. Basically, this argument is used to modify the text properties of pe chart.

The following is the syntax to change the font size of labels:

matplotlib.pyplot.pie(x, labels=[], textprops={"fontsize":10})

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt

# Define Data Coordinates

languages = ['Python', 'Ruby', 'Java', 'Php']
 
popularity = [40, 20, 10, 30]

# Change label fontsize

textprops = {"fontsize":15}

# Plot


plt.pie(popularity, labels=languages, textprops =textprops) 

# Display

plt.show() 
  • First, we import matplotlib.pyplot library for data visualization.
  • Next, we define data to coordinate to plot a pie chart.
  • After this, we create a list of labels to be added.
  • Then we create a dict where we set fontsize and its value as key and value to change the size of the label.
  • To create a pie chart, we use the pie() method, and to change the font size of labels we pass textprops argument to it.
  • To display the pie plot, we use the show() method.
matplotlib pie chart label fontsize
textprops{‘fontsize’:15}

Read: Matplotlib save as pdf

Matplotlib pie chart legend font size

Here we’ll see an example of a pie chart where we are going to change the fontsize of the legend. To change the fontsize we use the fontsize argument with the legend() method.

The following is the syntax:

matplotlib.pyplot.legend(labels, fontsize=None)

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

water_quantity = [17, 27, 14, 22, 16, 6]

# Add labels

water_uses = ['Shower', 'Toilet', 'Leaks', 'Clothes Wsher', 
              'Faucet', 'Other']

# Colors

colors = 
['salmon','palegreen','skyblue','plum','pink','silver']

# Plot

plt.pie(water_quantity, colors=colors)

# Add legend

plt.legend(labels=water_uses, fontsize=18, loc='upper center', 
           bbox_to_anchor=(0.5, -0.04), ncol=2)

# Display

plt.show() 
  • Firstly, define data coordinate to plot pie chart.
  • Then create a list of labels to define labels on the pie chart.
  • After this, we create a list of colors to change the colors of slices.
  • To plot a pie chart, we use the pie() method.
  • To add a legend to a pie chart, we use the legend() method, and to change the font size of the legend we use the fontsize argument.
matplotlib pie chart legend fontsize
plt.legend(fontsize=18)

Read: Matplotlib title font size

Matplotlib pie chart autopct

Here we’ll see an example of a pie chart with an autopct argument. The autopct parameter is used to display the percentage of the respective wedge. By default, the percentage labels are placed inside. The format string will be fmt%pct.

The following is the syntax:

matplotlib.pyplot.pie(x, labels=[], autopct=fmt%pct)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

cost = [10, 15, 15, 15, 20, 25]

# Define Label

work = ['Timber', 'Supervision', 'Steel', 'Bricks', 'Cement', 
        'Labour']
 
# Plot with autopct

plt.pie(cost, labels=work, autopct='%.1f%%') 

# Display


plt.show()
  • We define cost as a data coordinate to plot a pie chart.
  • To define labels in a pie chart, we create a work list.
  • To plot a pie chart, we use the pie() function.
  • To add a percentage inside the wedges, we pass the autopct argument to the pie() method.
matplotlib pie chart autopct
plt.pie(autopct= fmt%pct )

Read: Matplotlib scatter plot color

Matplotlib pie chart autopct position

Here we’ll see an example of a pie chart where we manually set the position of percentage labels. To change the position of the autopct, we use the pctdistance and labeldistance arguments.

The syntax is as below:

matplotlib.pyplot.pie(x, labels, autopct, pctdistance, 
                      labeldistance)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

cost = [10, 15, 15, 15, 20, 25]

# Define Label

work = ['Timber', 'Supervision', 'Steel', 'Bricks', 'Cement', 
        'Labour']
 
# Plot with autopct position

plt.pie(cost, labels=work, autopct='%.1f%%',pctdistance=1.7, 
        labeldistance=1.2) 

# Display

plt.show()

To set the position of the percentage labels outside the wedges, we pass the pctdistance and labeldistance argument to the pie() method.

matplotlib pie chart autopct position
plt.pie(pctdistance=1.7, labeldistance=1.2)

Read: Matplotlib Plot NumPy Array

Matplotlib pie chart wedgeprops

Here we’ll see an example of a pie chart wedgeprops argument. Basically, this argument is used to modify the properties of wedges in the pie chart.

The syntax is as fellow:

matplotlib.pyplot.pie(x, wedgeprops={}

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

popularity = [20, 15, 35, 26, 16]

# Define Label

beverages = ['Tea','Coffee', 'Cola', 'Water', 'Other']

# color

colors=['gold', 'springgreen', 'powderblue', 'orchid', 
        'slategray']

# Plot with wedgeprops

plt.pie(popularity, labels=beverages, 
        wedgeprops={'edgecolor':'k', 'linestyle': 'dashdot',    
        'antialiased':True} 
,colors=colors)

# Add title

plt.title('Favourite Beverages',fontweight='bold')

# Display

plt.show()
  • Firstly, import matplotlib.pyplot library.
  • Next, define the x data coordinate to create a pie chart.
  • To add labels, create a list of labels.
  • To change the colors of slices, use the colors argument and pass a list of colors to it.
  • To plot a pie chart, use the pie() method.
  • To change the properties of wedges, use the wedgeprops argument. Here we change the linestyle of the wedges.
  • To add a title to the plot, use the title() method.
matplotlib pie chart wedgeprops
plt.pie(wedgeprops={})

Read: Matplotlib set_xticklabels

Matplotlib pie chart edge color

Here we’ll see an example of a pie chart with different edgecolor. To change the color of the edges, we use the wedgeprops argument and create a dictionary with edgecolor as key and color as value.

The following is the syntax:

matplotlib.pyplot.pie(x, wedgeprops={'edgecolor':None})

Let’s have a look at an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

popularity = [20, 16, 35, 9]

# Define Label

books = ['Story Books','Comic Books', 'Puzzel Books', 'Poem Books']

# color

colors=['rosybrown', 'moccasin', 'lightyellow', 'darkseagreen']

# Plot with different edgecolor

plt.pie(popularity, labels=books, wedgeprops=
       {'edgecolor':'maroon'}, colors=colors)

# Add title

plt.title('Favourite Books',fontweight='bold')

# Display

plt.show()
  • Here we create a pie chart which tells about popularity of books among children’s. To change the edge color of the pie wedgeprops argument is passed to the pie() method.
  • Wedgeprops argument takes values in dict so, we create a dictionary that defines edgecolor. Here we set the edge color to maroon.
matplotlib pie chart edge color
wedgeprops={‘edgecolor’:’maroon’}

Read: Matplotlib set_xticks

Matplotlib pie chart increase size

We’ll increase the size of the pie chart by increasing a size of a figure.

The following is the syntax:

matplotlib.pyplot.figure(figsize=(x,y))

Here x and y represent width and height respectively.

Example:

# Import Library

import matplotlib.pyplot as plt

# Figure Size


plt.figure(figsize=(8,10))

# Define Data Coordinates

popularity = [30, 20, 13, 27, 10]

# Define Label

fruits = ['Banana','Pineapple', 'Orange', 'Grapes', 'Peach']

# Color

colors=['rosybrown', 'moccasin', 'lightyellow', 'darkseagreen', 
        'lavender']

# Plot


plt.pie(popularity, labels=fruits, colors=colors)

# Add title


plt.title('Favourite Fruits',fontweight='bold')

# Display


plt.show()

To increase the size of the pie chart, we pass figsize parameter to the figure() method of pyplot.

matplotlib pie chart increase size
figsize=(8,10)

Read: Matplotlib fill_between – Complete Guide

Matplotlib pie chart labels inside

Here we’ll see an example of a pie chart with labels inside the slices. To add labels inside, we pass labeldistance parameter to the pie() method and set its value accordingly.

The following is the syntax:

matplotlib.pyplot.pie(x, labeldistnce=0.5)

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt

# Define Data Coordinates

popularity = [25, 34, 25, 8, 8]

# Define Label

activities = ['Sleeping', 'School', 'Playing', 'Tv', 'Music']

# color


colors=['lightcoral', 'sandybrown', 'gold', 'darkseagreen', 
        'lavender']

# Plot 

plt.pie(popularity, labels=activities, colors=colors, 
        labeldistance=0.5)

# Add title

plt.title('Activities',fontweight='bold')

# Display


plt.show()
matplotlib pie chart labels inside
plt.pie(labeldistance=0.5)

Read: Matplotlib set_yticklabels – Helpful Guide

Matplotlib pie chart bold text

We’ll see an example of a pie chart where we bold the label text. To bold the text, we pass textprops argument to the pie() method.

The following is the syntax:

matplotlib.pyplot.pie(x, textprops={'fontweight':'bold'})

Example:

# Import Library


import matplotlib.pyplot as plt

# Figsize

plt.figure(figsize=(6,8))

# Define Data Coordinates

owner = [10, 45, 15, 30]

# Define Label

transport = ['Bicycle', 'Walking', 'Bus', 'Car']

# Plot 

plt.pie(owner, labels=transport, textprops=
        {'fontweight':'bold'})

# Add title

plt.title('Types of Transport',fontweight='bold')

# Display

plt.show()
matplotlib pie chart bold text
plt.pie(textprops={fontweight:bold})

Read: Matplotlib tight_layout – Helpful tutorial

Matplotlib pie chart bigger

We’ll see an example of how we can create a bigger pie chart.

Example:

# Import Library

import matplotlib.pyplot as plt

# Figsize

fig = plt.figure()
fig.set_figheight(10)

# Define Data Coordinates

population = [29, 29, 42]

# Define Label

wildlife = ['Whales', 'Bears', 'Dolphins']

# Plot 

plt.pie(population, labels=wildlife)

# Add title

plt.title('Wildlife Population',fontweight='bold')

# Display

plt.show()

Here we only increase the height of the pie chart. To increase height, we use set_figheight() method of figure() method.

matplotlib pie chart bigger
set_figheight()

Read: Python Matplotlib tick_params

Matplotlib pie chart textprops

Here we’ll learn about the textprops argument of the pie chart. We’ll use the textprops argument to style texts respectively.

The following is the syntax:

matplotlib.pyplot.pie(x, textprops={})

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates


sales = [22, 33, 13, 15, 17]

# Define Label


laptops = ['HP', 'Dell', 'Lenovo', 'Asus', 'Acer']

# Text Properties


text_prop = {'family':'sans-serif', 'fontsize':'x-large', 
             'fontstyle':'italic', 'fontweight':'heavy'}

# Plot 


plt.pie(sales, labels=laptops, textprops=text_prop)

# Add title


plt.title('Sales',fontweight='bold')

# Display


plt.show()
  • First, import matplotlib.pyplot library.
  • Then define the data coordinate used for making a pie chart.
  • We also create a list of labels.
  • After this, we create a dictionary defining the text properties.
  • To create a pie chart, we use the pie() method of pyplot module. We also pass the textprops argument to change text properties of text.
  • We also use the title() method to add a title to a plot.
matplotlib pie chart textprops
plt.pie(textprops={})

Read: Matplotlib x-axis label

Matplotlib pie chart text color

Here we’ll see an example of a pie chart with labels and in this example, we’ll change the color of labels.

Syntax to change color:

matplotlib.pyplot.pie(x, textprops={'color':None})

Example:

# Import Library


import matplotlib.pyplot as plt

# Define Data Coordinates


popularity = [25, 16, 23, 12, 35]

# Define Label

sports = ['Football', 'Basketball', 'Badminton', 'Hockey', '       
          'Cricket']

# Color

colors = ['orchid','mediumpurple', 'powderblue', 
          'mediumaquamarine', 'sandybrown']

# Plot 

plt.pie(popularity, labels=sports, colors=colors, 
        textprops={'color':'darkblue'})

# Add title

plt.title('Favourite Sports',fontweight='bold')

# Display

plt.show()

To change the color of text, we create a dictionary defining the color as key and darkblue as value and we pass this dictionary i.e. textprops argument to the pie() method.

matplotlib pie chart text color
textprops={‘color’:’darkblue’}

Read: Matplotlib multiple bar chart

Matplotlib pie chart hatch

In this section, we’ll learn about pie chart hatch. We have already studied about pie chart in the above topics. Now it’s time to learn something new i.e. hatch.

In every case, we use the colors to fill the pie chart, but now we learn to fill patterns in every slice of the pie chart.

To fill the plots with a pattern, we assign a new parameter hatch with values as a string. Some of the string values are: / , \\ , | , – + , x , o. , *

Source Code:

# Import Library


import matplotlib.pyplot as plt
import numpy as np

# Define Data Coordinates

data = np.random.rand(4)

# Hatch


hatches = ['..' for value in data]

# Plot pie chart

pie_chart = plt.pie(data)

# Fill hatch

for i in range(len(pie_chart[0])):
    pie_chart[0][i].set(hatch = hatches[i], fill=False)
    
# Display

plt.show()
  • First, we import matplotlib.pyplot, and numpy libraries.
  • Next, we define data using numpy random.rand() function to plot pie chart.
  • After this, we define the hatch pattern.
  • To plot a pie chart, we use the pie() method.
  • To fill the pie with hatch patterns, we use for loop and also pass fill parameter and set its value to False to get the blank background.
matplotlib pie chart hatch
hatch=[‘..’]

Read: Matplotlib plot_date – Complete tutorial

Matplotlib pie chart alpha

In this section, we’ll see an example of a pie chart with an alpha argument. The alpha argument is used to set the transparency of the colors. Its value range from 0 to 1.

To use an alpha argument, we have to call a wedgeprops argument and create a dictionary, and set alpha argument as a key and value of alpha as a value.

The syntax is given below:

matplotlib.pyplot.pie(x, wedgeprops={'alpha':1})

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt

# Define Data Coordinates


loss = [14, 32, 15, 11, 28]

# Define Label


reasons = ['Competition', 'Not qualified', 'Salesperson', 
           'Price', 'Timing']

# Plot 

plt.pie(loss, labels=reasons, wedgeprops={'alpha':0.5})

# Add title


plt.title('Loss Reasons',fontweight='bold')

# Display

plt.show()
matplotlib pie chart alpha
plt.pie(wedgeprops={‘alpha’:0.5})

Read: Matplotlib subplots_adjust

Matplotlib pie chart explode

Here we’ll learn about the pie chart explode argument. Using the explode parameter, we may make one or more slices of the pie chart pop out.

Let’s start by declaring an array with the explosion values. Each slice is offset by a fraction of the radius specified in the explosion array.

The syntax is as fellow:

matplotlib.pyplot.pie(x, explode=())

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates


cost = [18, 13, 11, 9, 6, 21, 25]

# Define Label


project = ['Labor','Licenses','Taxes','Legal','Insurance',
           'Facilities','Production']

# Explosion Value

explode = (0.2, 0, 0, 0, 0, 0, 0)

# Plot 

plt.pie(cost, labels=project, explode=explode)

# Add title

plt.title('Project Cost Breakdown',fontweight='bold')

# Display


plt.show()
  • Define data coordinate and labels to create a pie chart.
  • After this, we define explosion value.
  • To create a pie chart, use the pie() method and pass explode parameter to it.
matplotlib pie chart explode
plt.pie(explode=())

Read: Matplotlib subplot tutorial

Matplotlib pie chart shadow

In this section, we’ll add a shadow to the pie chart using the shadow argument. By default the value of the shadow argument is False.

The following is the syntax:

matplotlib.pyplot.pie(x, shadow=True)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data Coordinates

defects = [14, 11, 15, 35, 25]

# Define Label


parts = ['Rimcut', 'Bulge', 'Other', 'Dented Rim', 'Dented 
         Body']

# Explosion Value


explode = (0.1, 0.1, 0.1, 0.1, 0.1)

# Plot 


plt.pie(defects, labels=parts, explode=explode, shadow=True)

# Add title

plt.title('Project Cost Breakdown',fontweight='bold')

# Display

plt.show()
matplotlib pie chart shadow
plt.pie(shadow=True)

Also, check: module ‘matplotlib’ has no attribute ‘artist’

Matplotlib pie chart frame

By setting the frame parameter to True, we can draw a frame around the pie chart.

The following is the syntax:

matplotlib.pyplot.pie(x, frame=True)

Example:

# Import Library

import matplotlib.pyplot as plt

# Create subplot

figure , ax = plt.subplots()

# Define Data Coordinates

sales = [35, 12, 20, 22, 32 ]

# Define Label

company = ['Redmi', 'Apple', 'Samsung', 'Oppo', 'Vivo']

# Plot 

plt.pie(sales, labels=company, frame=True)

ax.axis('equal')

# Add title

plt.title('Sales of different company',fontweight='bold')

# Display

plt.show()
  • Import matplotlib.pyplot library.
  • Create subplot, using subplots() method.
  • Define data coordinates and labels.
  • To plot a pie chart, we use the pie() method.
  • To set a frame around a chart, we pass frame arguemnt to method and set its value True.
  • Set axis to equal.
  • To add a title, we use the title() method.
matplotlib pie chart frame
plt.pie(frame=True)

Numpy matplotlib pie chart

Here we’ll see an example of a pie chart using NumPy.

Example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define Data Coordinate

x = np.array([20, 12, 9, 3])

# Plot pie chart

plt.pie(x)

# Display


plt.show()
  • Here we import matplotlib.pyplot and numpy library.
  • Next, we define data coordinates to create numpy using array() method.
  • To plot a pie chart, we use plot() method of pyplot module.

Output:

numpy matplotlib pie chart
np.array([])

Matplotlib pie chart label header

In this section, we’ll see an example of a pie chart with a header label. To add a header to the legend, we use the legend() function with the title parameter.

The following is the syntax:

matplotlib.pyplot.legend(title)

Let’s see an example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates and labels

quantity = np.array([1, 4, 3, 2])
material = ['Butter', 'Egg', 'Flour', 'Sugar']

# Plot pie chart

plt.pie(quantity, labels = material)

# Legend with header

plt.legend(title = "Butter Cake:", loc='upper center', 
           bbox_to_anchor=(0.5, -0.04))

# Display

plt.show() 
  • Here we create a pie chart to represent butter cake recipe material quantity by using pie() method.
  • To add a legend with header, we use legend() method with title parameter.
matplotlib pie chart label header
plt.legend(title=)

Matplotlib multiple pie chart

Here we’ll create multiple pie charts using the figure() method of pyplot module.

Example:

# Import Library

import matplotlib.pyplot as plt

# Create first chart.

plt.figure(0)
x = [30, 30, 15, 11, 12]
reasons = ['Health','Less Pollution', 'No parking Ptoblem', 'No costs', 'Faster than driving']
plt.pie(x, labels = reasons, explode=(0.1, 0.1, 0.1, 0.1, 0.1), 
        autopct='%.1f%%')
plt.title('Reasons for cycling', color='r')

# Create second chart.

plt.figure(1)
x = [40, 21, 14, 14, 11]
reasons = ['Comfort','Distance', 'Faster than cycling', 'Need to carry things to work', 'Safer than cycling']
plt.pie(x, labels = reasons, explode=(0.1, 0.1, 0.1, 0.1, 0.1), 
        autopct='%.1f%%')
plt.title('Reasons for driving', color='r')

# Show all figures

plt.show() 

Steps to create multiple pie charts:

  • Import matplotlib.pyplot library.
  • Create first pie chart, using figure() method.
  • Define coordinate x to create first pie chart.
  • Next define labels for first pie chart.
  • To plot a pie chart, we use the pie() method.
  • We also pass explode and autopct argument to the pie() method to get cut off of slices and to show percentage of slices respectively.
  • To add a title, we use the title() method.
  • Simirally, we create second pie chart, using figure() method.
matplotlib multiple pie chart
Multiple Pie Chart

Read: Matplotlib xlim – Complete Guide

Matplotlib pie chart move legend

Here we’ll learn to move legend in the pie chart. To change the position of legends we pass the loc parameter to the legend() method.

The syntax is given below:

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

teachers = [15, 24, 13, 15, 10]
subjects = ['Science', 'Mathematics', 'Social Studies', 
            'English', 'Spanish']

# Plot pie chart

plt.pie(teachers)

#  Move Legend 


plt.legend(subjects, title = "Subjects Alloted To Teachers:", loc='lower right',bbox_to_anchor=(0.3, -0.08))

# Display


plt.show()

Explanation:

To move a legend we pass loc and bbox_to_anchor parameters to the legend method to set the location and manual position of legends.

matplotlib pie chart move legend
plt.legend(loc=’lower right’, bbox_to_anchor=(0.03, -0.08))

Matplotlib pie chart move labels

Here we’ll learn to move labels in a pie chart. To change the position of labels, we pass the labeldistance parameter to the pie() method. By default, its position is 1.1 from a radial distance.

The following is the syntax:

matplotlib.pyplot.pie(x, labeldistance=1.1)

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates and labels


winner = [19, 27, 13, 41]
superhero = ['Captain America', 'Iron Man', 'Superman', 
             'Batman']

# Plot pie chart

plt.pie(winner, labels = superhero, labeldistance=1.35)

# Title

plt.title('Superhero Battle Winner', color='r')

# Display

plt.show() 

In this example, we set the labeldistance to 1.35 from a radial distance by passing the labeldistance argument to the method.

matplotlib pie chart move labels
plt.pie(labeldistance=1.35)

Matplotlib pie chart not circle

By default, the pie chart is circular in shape, but if you want to change the shape of the pie chart, you must pass explode parameter to the pie() method and set different explosive values.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = np.random.rand(3)

# Plot pie chart

plt.pie(x, explode=(0.5, 0.65, 0.5))

# Display

plt.show() 
matplotlib pie chart not circle
Pie but not circle

Matplotlib pie chart side by side

To create pie charts side by side, we use the subplot function of pyplot module in Matplotlib.

The following is the syntax:

matplotlib.pyplot.subplot(nrows, ncolumns, index)

Example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates and labels

energy = ['Coal','Other','Nuclear','Petro','Gas']
production_1995 = [30, 5, 7, 30, 30]
production_2005 = [31, 10, 11, 20, 31]

# using subplot function and creating plot one
# row 1, column 2, count 1 subplot

plt.subplot(1, 2, 1)  
plt.pie(production_1995,labels=energy)
plt.title('1995',color='b')

# using subplot function and creating plot two
# row 1, column 2, count 2

plt.subplot(1, 2, 2)
plt.pie(production_2005,labels=energy)
plt.title('2005',color='b')

# space between the plots

plt.tight_layout()
 
# show plot

plt.show()
  • In the above example, we define data coordinates and labels used to plot pie chart.
  • Using subplot() function and setting its row, column, and count to 1, 2, 1 we create first subplot.
  • Using subplot() function and setting its row, column, and count to 1, 2, 2 we create second subplot on the side of first one.
  • To plot a pie chart, we use pie() function.
  • To add a title to a pie chart, we use title() function.
  • To add a space between plots, we use tight_layout() function.
  • To display a chart, we use show() function.
matplotlib pie chart side by side
plt.subplot()

Matplotlib pie chart clockwise

Here we’ll learn about the clockwise mode of a pie chart. For this, you must set counterclock parameter to False. By default, its value is True.

The syntax is as given below:

matplotlib.pyplot.pie(x, counterclock=False)

Example:

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

ratio = [20, 12, 4, 18, 16]
responses = ['Likely','Very Likely','Very Unlikely', 
             'Unlikely', 'Unsure']

# Plot pie chart

plt.pie(ratio, labels = responses,counterclock=False, autopct='%1.1f%%')

# Title

plt.title('Survey Responses', color='r')

# Display

plt.show()
matplotlib pie chart clockwise
plt.pie(counterclock=False)

Matplotlib pie chart save

Here we’ll learn to save the pie chart as a png image. To save a plot, we have to use savefig() method.

Example:

# Import Library

import matplotlib.pyplot as plt

# Create subplot


figure , ax = plt.subplots()

# Define Data Coordinates


sales = [35, 12, 20, 22, 32 ]

# Define Label

company = ['Toyota','General Motors', 'Honda', 'Ford', 'Fiat']

# Plot 

plt.pie(sales, labels=company, frame=True)

ax.axis('equal')

# Add title


plt.title('Sales of different company',fontweight='bold')

# Save pie chart

plt.savefig('Save Pie Chart.png')

# Display


plt.show()
matplotlib pie chart save
plt.savefig()

Matplotlib pie chart turn off labels

Here we’ll see an example where we turn off labels of a pie chart based on some conditions.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates and labels

hours = [6, 8, 4, 3, 3]
activities = ['School', 'Sleep', 'Homework', 'Others', 'Play']

# Plot pie chart

plt.pie(hours,labels=activities, autopct=lambda p: format(p, 
        '.2f') if p > 15 else None)

# Title

plt.title('Time', color='r')

# Display

plt.show() 
  • Import matplotlib.pyplot library.
  • Define data coordinates and labels to create pie chart.
  • To plot a pie chart, we use pie() method.
  • To add a title, we use title() method.
  • We apply conditional removal of labels, such that if %age value is greater than 15, then only keep labels, otherwise remove them.
matplotlib pie chart turn off labels
plt.pie()

Matplotlib pie chart from dataframe

Here we’ll learn to create a pie chart from pandas dataframe. A proportionate representation of numerical data in a column is a pie plot.

The following steps are required to create a pie chart from dataframe:

  • Import the required libraries such as pandas and matplotlib.pyplot.
  • Create pandas dataframe using DataFrame() method of pandas.
  • Plot a pie chart for the Amount column with Expenses Column using the pie() method.
matplotlib pie chart from dataframe
pd.DataFrame()

Matplotlib nested pie chart with labels

Here we’ll see an example of a nested pie chart with labels. We can use a nested pie chart or a multi-level pie chart to include multiple levels or layers in your pie. Nested pies are a form of the pie chart that is a module variation of our normal pie chart.

Let’s see an example:

# Import Libraries

import matplotlib.pyplot as plt

# Define data coordinates and labels

labels = ['Vitamin B12', 'Vitamin A', 'Vitamin E']
sizes = [600, 600, 600]
labels_vitamins = ['meat','poultry','fish','carrots','sweet potatoes','spinach','kale','nuts','seeds','vegetable oils']
sizes_vitamins = [120, 120, 120, 120, 120, 120, 120, 120, 120, 120]

# Define colors

colors = ['#8B8378', '#53868B','#2E8B57']
colors_vitamins = ['#EEDFCC', '#FFEFDB', '#FAEBD7', '#7AC5CD',
                    '#8EE5EE','#98F5FF', 
                  '#5F9EA0','#43CD80','#4EEE94','#54FF9F']

# Plot pie chart

bigger = plt.pie(sizes, labels=labels, colors=colors,startangle=90)
smaller = plt.pie(sizes_vitamins,       labels=labels_vitamins,radius=0.7,startangle=90,labeldistance=0.8,colors=colors_vitamins)

# Add space

plt.axis('equal')
plt.tight_layout()

# Display

plt.show()
  • First import matplotlib.pyplot library.
  • Next define outer labels, inner labels, outer size, inner size, inner color, and outer color of the pie slices.
  • By using the plt.pie() method we create an inner and outer pie chart.
matplotlib nested pie chart with labels
Nested Pie Chart

Matplotlib pie chart remove labels

Here we’ll learn to remove axes labels from the pie chart. To remove the labels we pass a blank string to the axes function.

Let’s see an example first where we add labels:

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

hours = [6, 8, 4, 3, 3]
activities = ['School', 'Sleep', 'Homework', 'Others', 'Play']

# Plot pie chart

plt.pie(hours,labels=activities, autopct=lambda p: format(p, '.2f') if p > 15 else None)

# Labels

plt.xlabel("Activities", color='g')
plt.ylabel("Hours", color='g')

# Title


plt.title('Time', color='r')

# Display

plt.show() 

To add labels at x-axis and y-axis we use, xlabel() and ylabel() functions.

matplotlib pie chart remove labels 1
plt.xlabel() and plt.ylabel()

Let’s see an example where we remove labels:

To remove labels at axes, we pass a blank string.

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

hours = [6, 8, 4, 3, 3]
activities = ['School', 'Sleep', 'Homework', 'Others', 'Play']

# Plot pie chart

plt.pie(hours,labels=activities, autopct=lambda p: format(p, '.2f') if p > 15 else None)

# Remove Labels

plt.xlabel(" ")
plt.ylabel(" ")

# Title

plt.title('Time', color='r')

# Display

plt.show() 
matplotlib remove labels from pie chart
plt.xlabel(” “) and plt.ylabel(” “)

Matplotlib pie chart radius

Here we’ll see an example where we create a pie with a different radius. By passing radius as an argument to the pie() method, we can increase and decrease the size of a pie chart.

The following is the syntax:

matplotlib.pyplot.pie(x, labels, radius)

Example:

# Import Library

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Define data coordinates and labels

monthly_sales = [8, 30, 10, 27, 25]
stores = ['B2B Channels', 'Discounts Sales', 'Others', 'Digital 
           Stores', 'Off-line Stores']

# Plot pie chart

plt.pie(monthly_sales, labels=stores, radius=1.6)

                       #  OR

plt.pie(monthly_sales, labels=stores, radius=0.5)

# Display

plt.show()
  • First create subplot, using subplots() function.
  • Next, we define data coordinates and labels.
  • To plot a pie chart, we use the pie() function.
  • To set the radius, we pass radius argument to function. Here we set radius to 1.6 and 0.5 in respective cases.
matplotlib pie chart radius
plt.pie(radius=1.6)
matplotlib pie chart with radius
plt.pie(radius=0.5)

Matplotlib pie chart rotate labels

Here we’ll learn to rotate labels plotted in a pie chart. To rotate labels, we pass rotatelabels to the pie() function.

The following is the syntax:

matplotlib.pyplot.pie(x, labels, rotatelabels)

Example:

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

popularity = [2, 3, 6, 35, 54]
devices = ['iPod Touch', 'Samsung SGH-1747M', 'RIM Playbook', 
            'iPhone', 'iPad']

# Plot pie chart


plt.pie(popularity, labels=devices, rotatelabels=180)

# Display


plt.show() 
  • We import matplotlib.pyplot library.
  • Next, we define data coordinates and labels.
  • To plot a pie chart, we use pie() function.
  • To rotate labels, we pass rotatelabels argument to the method. We rotate the labels to 180 degrees.
matplotlib pie chart rotate labels
plt.pie(rotatelabels=180)

Matplotlib pie chart subplots

Here we’ll see an example of multiple pie charts in a figure area. To create subplots, we use the subplots() function of the axes module.

Example:

# Importing Library

import matplotlib.pyplot as plt
import numpy as np

# Create subplots

fig, ax = plt.subplots(2, 2)

# Define Data

data1 = [10, 60, 30]
data2 = np.array([50])
data3 = np.random.rand(8)
data4 = [10, 10, 10, 10, 10, 10]

# Plot graph

ax[0, 0].pie(data1)
ax[0, 1].pie(data2)
ax[1, 0].pie(data3)
ax[1, 1].pie(data4)

# Add Title

ax[0, 0].set_title('Pie Chart 1')
ax[0, 1].set_title('Pie Chart 2')
ax[1, 0].set_title('Pie Chart 3')
ax[1, 1].set_title('Pie Chart 4')

# Display Graph

fig.tight_layout()
plt.show()
  • To create subplots with 2 rows and 2 columns, we use subplots() function.
  • Next, we define data coordinates.
  • To plot the pie chart, we use pie() function of axes module.
  • To set the title, we use set_title() function.
  • To add space between the plots, we use tight_layout() function.
  • To show the graph, we use show() function.
matplotlib pie chart subplots
plt.subplots()

Matplotlib pie chart start angle

The start angle is set to the x-axis by default, but you can change it by giving a startangle argument.

The startangle parameter takes a degree angle as input; the default angle is 0:

The given syntax is:

matplotlib.pyplot.pie(x, labels, startangle)

Example:

# Import Library


import matplotlib.pyplot as plt

# Define data coordinates and labels

visitors = [40, 25, 15, 10, 10]
sources = ['Searches', 'Social Media', 'Links', 'Direct', 
           'Advertising']

# Plot pie chart


plt.pie(visitors, labels=sources, startangle=90)

                    # OR

plt.pie(visitors, labels=sources, startangle=270)

# Display


plt.show() 

Here we pass startangel argument to pie() function and set its value to 90 and 270 degrees respectively.

matplotlib pie chart startangle
plt.pie(startangle=90)
matplotlib pie chart with startangel
plt.pie(startangle=270)

Matplotlib pie chart dictionary

Here we’ll see an example where we create a pie chart by using dictionary datatype.

Example:

# Import Library

import matplotlib.pyplot as plt

# Data

pie_data = {'Chocolate': 65,
 'Tart': 30,
 'Fruit': 45,
 'Mint': 18, }

# Data to plot
            
flavors = []
popularity = []

for x, y in pie_data.items():
    flavors.append(x)
    popularity.append(y)

# Plot

plt.pie(popularity, labels=flavors)

# Display

plt.axis('equal')
plt.show()

In the above example, we define data coordinates by using dictionary datatype. Here we define a key as flavors and values as popularity.

matplotlib pie chart dictionary

Matplotlib half pie chart

Here we’ll see an example of a pie chart where we make a half pie chart.

Example:

# Import Library

import matplotlib.pyplot as plt

# Create Subplot


fig = plt.figure(figsize=(8,6),dpi=100)
ax = fig.add_subplot(1,1,1)

# Data Coordinates

pie_labels = ["Label 1", "Label 2", "Label 3"]
pie_values = [1,2,3]

# Colors

pie_labels.append("")
pie_values.append(sum(val))  
colors = ['red', 'blue', 'green', 'white']

# Plot

ax.pie(val, labels=label, colors=colors)

# Add artist

ax.add_artist(plt.Circle((0, 0), 0.6, color='white'))

# Display


plt.show()
  • We import matplotlib.pyplot library.
  • Next, we use figure() function to set fig size.
  • Then we use add_subplot() function to add subplot.
  • Define data coordinates and labels.
  • Then we append data and assign colors.
  • To plot pie chart, we use pie() function.
  • Then we add artist we use add_artist() function and circle() function.
matplotlib half pie chart
Half Pie Chart

Matplotlib pie chart absolute value

Here we’ll learn to replace auto-labeled values with absolute values. To turn the percentage into original values we have to multiply the total size of the pie and divide it by 100.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates and labels

money_utilised = [48, 19, 9, 9, 10, 5]
resources = ['Rent', 'Food', 'Utilities', 'Fun', 'Clothes', 
             'Phone']

# Total

total = sum(money_utilised)

# Plot pie chart

plt.pie(money_utilised, labels=resources,
         autopct=lambda p: '{:.0f}'.format(p * total / 100))

# Display

plt.show()

Output:

matplotlib pie chart absolute value
Absolute Value

Matplotlib pie chart donut

The modified version of a Pie chart is Donut Chart. Donut chart having the area of center cut out.

Example:

# Import Library

import matplotlib.pyplot as plt

# Data coordinates and labels

languages = ["Python", "Android", "Php", "JavaScript"]
popular = [50, 15, 45, 30]
colors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F']

# Plot pie chart

plt.pie(popular, labels=languages, colors=colors)

# Draw circle


centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
  
# Adding Circle in Pie chart


fig.gca().add_artist(centre_circle)

# Display


plt.show()
  • Firstly, we import library matplotlib.pyplot.
  • Next, we define data coordinates, labels and colors.
  • After this, we plot pie chart using pie() function.
  • Then we draw circle using circle() function.
  • To add a circle in a pie chart we use add_artist() function.
matplotlib pie chart donut
Donut

Matplotlib pie chart annotation

Here we’ll learn to create a pie chart with annotated labels.

Example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np 

# Subplot

fig, ax= plt.subplots(figsize=(4,4))
plt.subplots_adjust(bottom=0.3)

# Coordinates and labels

usage = [19, 36, 39, 5, 3]
browser = ['Internet Explorer', 'Firefox', 'Chrome', 'Safari', 
           'Opera']

# Title


plt.title('Browser Usage')
plt.gca().axis("equal")

# Plot pie

patches, texts = pie = plt.pie(usage)

# Annotate

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
arrowprops=dict(arrowstyle="-",connectionstyle="angle,angleA=0,angleB=90")
kw = dict(xycoords='data',textcoords='data',arrowprops=arrowprops, 
          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(patches):
    ang = (p.theta2 - p.theta1)/2.+p.theta1
    y = np.sin(ang/180.*np.pi)
    x = 1.35*np.sign(np.cos(ang/180.*np.pi))
    plt.gca().annotate(str(1+i), xy=(0, 0), xytext=( x, y), **kw )

# Legend


plt.legend(pie[0],browser, loc="center", bbox_to_anchor=(0.5,-0.2))

# Display


plt.show()
matplotlib pie chart annotation

Matplotlib pie chart categorical data

Here we’ll learn to plot a pie chart for categorical data by using groupby() function.

Example:

# Import Library

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

# function

def label_function(val):
    return f'{val / 100 * len(df):.0f}\n{val:.0f}%'

# Data Frame


N = 50
df = pd.DataFrame({'vegetable': np.random.choice(['Tomato','Carrot', 'Peas'], N),
                   'fruit': np.random.choice(['Apple', 
                   'Orange', 'Cherry'], N)})

# create subplot


fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

# Categorial data pie chart

df.groupby('vegetable').size().plot(kind='pie', colors='
           ['tomato', 'gold', 'skyblue'], ax=ax1)
df.groupby('fruit').size().plot(kind='pie', colors=
           ['violet','pink', 'lime'], ax=ax2)

# Labels


ax1.set_ylabel('Vegetables', size=15)
ax2.set_ylabel('Fruits', size=15)

# Auto space


plt.tight_layout()

# Display


plt.show()
matplotlib pie chart categorical data
df.groupby()

Also, take a look at some more tutorials on matplotlib.

So, in this Python tutorial, we have discussed the “Matplotlib Pie Chart” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib pie chart in python
  • Matplotlib pie chart example
  • Matplotlib pie chart title
  • Matplotlib pie chart title position
  • Matplotlib pie chart title font size
  • Matplotlib pie chart colors
  • Matplotlib pie chart with labels
  • Matplotlib pie chart background color
  • Matplotlib pie chart hex color
  • Matplotlib pie chart with legend
  • Matplotlib pie chart label fontsize
  • Matplotlib pie chart legend fontsize
  • Matplotlib pie chart autopct
  • Matplotlib pie chart autopct position
  • Matplotlib pie chart wedgeprops
  • Matplotlib pie chart edge color
  • Matplotlib pie chart increase size
  • Matplotlib pie chart labels inside
  • Matplotlib pie chart bold text
  • Matplotlib pie chart bigger
  • Matplotlib pie chart textprops
  • Matplotlib pie chart text color
  • Matplotlib pie chart hatch
  • Matplotlib pie chart alpha
  • Matplotlib pie chart explode
  • Matplotlib pie chart shadow
  • Matplotlib pie chart frame
  • Numpy matplotlib pie chart
  • Matplotlib pie chart label header
  • Matplotlib multiple pie chart
  • Matplotlib pie chart move legend
  • Matplotlib pie chart move labels
  • Matplotlib pie chart not circle
  • Matplotlib pie chart side by side
  • Matplotlib pie chart save
  • Matplotlib pie chart turn off labels
  • Matplotlib pie chart from dataframe
  • Matplotlib nested pie chart with labels
  • Matplotlib pie chart remove labels
  • Matplotlib pie chart radius
  • Matplotlib pie chart rotate labels
  • Matplotlib pie chart subplots
  • Matplotlib pie chart start angle
  • Matplotlib pie chart dictionary
  • Matplotlib half pie chart
  • Matplotlib pie chart absolute value
  • Matplotlib pie chart donut
  • Matplotlib pie chart annotation
  • Matplotlib pie chart categorical data