How to add labels to a pie chart using Matplotlib in Python

Overview

A pie chart is a graphic representation of quantitative information by means of a circle divided into sectors, in which the relative sizes of the areas (or central angles) of the sectors correspond to the relative sizes or proportions of the quantities.

To create a pie chart in Matplotlib we use the pie() method.

Creating a pie chart

The pie() method takes the parameter value data array which represents the wedge sizes of the pie chart.

Code

from matplotlib.pyplot import pie, show
from numpy import array
data_set = array([50, 20, 25, 15])
pie(data_set)
show()

Explanation

  • Line 1: We import the pie() and show() functions from matplotlib.pyplot module.

  • Line 2: We import the array() function from NumPy library.

  • Line 4: We use the array() method to create a data array.

  • Line 6: We use the pie() method to plot a pie chart.

  • Line 7: We use the show() method to show our plot.

Adding a label to a pie chart

To add a label to a pie chart, the pie() function must take another parameter value called labels.

Syntax

pie(x, labels)

Code

from matplotlib.pyplot import pie, show
from numpy import array
data_set = array([50, 20, 25, 15])
my_labels = ["Tomatoes", "Apples", "Mangoes", "Tiger nuts"]
pie(data_set, labels = my_labels)
show()

Code explanation

  • Line 1: We import the pie() and show() functions from matplotlib.pyplot module.

  • Line 2: We import the array() function from NumPy library.

  • Line 4: We use the array() method to create a data array data_set.

  • Line 5: We create a list variable my_labels which will serve as the value for the label parameter.

  • Line 7: We use the pie() method to plot the data array data_set and pass the variable my_labels as the labels parameter value.

  • Line 8: We use the show() method to show our plot.

Free Resources