How to explode a pie chart using Matplotlib in Python
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 pltimport numpy as npy = 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()
Explanation
- Line 1: We import the library
matplotliband modulepyplot. - Line 2: We import the
numpylibrary. - Line 4: We create our data array variable
y. - Line 5: We create a list variable
mylabelsthat will represent the label parameter of thepie()method. - Line 6: We create a list variable
myexplodethat contains values which represents theexplodeparameter of thepie()method. - Line 8: We use the
pie()method to create a pie chart with parameter valuesx,labels, andexplode.
Note: When we create the
escapevalues inmyexplodevariable, the first value is given as0.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 pltimport numpy as npy = 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()
Explanation
In the code above, we can see that the wedges of the pie chart were given different values, unlike the first code example.