How to create a pie chart using Matplotlib in Python

Overview

A pie chart is a pictorial graph in the shape of a circle, with different wedges or segments representing different data values.

We draw pie charts in matplotlib using the method pie(), which is found in the pyplot module.

Syntax

pyplot.pie()

Parameter value

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

Code example

Now let’s explore a basic example of pie chart.

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

Code explanation

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

  • Line 2: We import array() 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.

After exploring the basic example, let's enhance our understanding with an example of a pie chart with some customization.

from matplotlib.pyplot import pie, show
from numpy import array
data_set = array([25, 20, 50, 15])
labels = ['A', 'B', 'C', 'D']
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0, 0.1, 0, 0) # "explode" the second slice (B)
pie(data_set, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True)
show()
  • Line 1: This line imports the pie() and show() functions from the matplotlib.pyplot module. pie() is used to create pie charts, while show() is used to display the plot.

  • Line 2: Here, we import the array() function from the NumPy library. This function is used to create an array, a fundamental data structure in numerical computing.

  • Line 4: We define a dataset using the array() function. In this case, we create an array with values [25, 20, 50, 15], which represent the sizes of different slices in the pie chart.

  • Line 5: We defined am labels variable, which a list of strings (['A', 'B', 'C', 'D']) representing the labels assigned to each slice of the pie chart. These labels will be displayed next to their respective slices.

  • Line 6: We defined a variable called colors, which is a list of color names or RGB tuples (['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']) specifying the colors of the pie chart slices. Each color corresponds to a specific slice, providing visual differentiation.

  • Line 9: This line calls the pie() function to create a pie chart. We pass the data_set array as an argument to the function, which specifies the sizes of the slices in the pie chart.

  • Line 10: Finally, we call the show() function to display the plot on the screen. This function is necessary to actually render the plot and show it to the user.

Free Resources