Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matplotlib
python
communitycreator

How to explode a pie chart using Matplotlib in Python

Onyejiaku Theophilus Chidalu

Overview

To “explode” a pie chart means to make one of the wedges of the pie chart to stand out. To make this possible in matplotlib, we use the explode() parameter.

Syntax

pyplot(x,explode)

Parameter value

  • x: The data array.
  • explode: It is used to explode the pie chart. If specified, it must be an array with one value representing a value for each wedge of the pie chart.

The explode parameter value represents how far each wedge is from the center of the pie chart.

Example 1

import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])
mylabels = ["Tomatoes", "Mangoes", "Oranges", "Apples"]
myexplode = [0.2, 0, 0, 0]

plt.pie(y, labels = mylabels, explode = myexplode)
plt.show() 
Exploding a pie chart using the explode parameter

Explanation

  • Line 1: We import the library matplotlib and modulepyplot.
  • Line 2: We import the numpy library.
  • Line 4: We create our data array variable y.
  • Line 5: We create a list variable mylabels that will represent the label parameter of the pie() method.
  • Line 6: We create a list variable myexplode that contains values which represents the explode parameter of the pie() method.
  • Line 8: We use the pie() method to create a pie chart with parameter values x, labels, and explode.

Note: When we create the escape values in myexplode variable, the first value is given as 0.2. This represents how far the first wedge (Tomatoes) is from the center of the pie chart.
Interestingly, we can also increase the distance of other wedges of the pie chart.

Example 2

import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])
mylabels = ["Tomatoes", "Mangoes", "Oranges", "Apples"]
myexplode = [0.2, 0, 0.4,  0.1]

plt.pie(y, labels = mylabels, explode = myexplode)
plt.show() 
Exploding other wedges of the pie chart

Explanation

In the code above, we can see that the wedges of the pie chart were given different values, unlike the first code example.

RELATED TAGS

matplotlib
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring