How to add a shadow to a pie chart using Matplotlib in Python
Overview
To add a shadow to the wedge of a pie chart, we use the shadow parameter, which is added as a parameter value to the pie() method.
Syntax
pie(x, shadow)
Parameter value
-
x: The data array to be represented on the pie chart -
shadow: This is used to add the shadow to the pie chart. It takes theTruevalue.
The wedge of the pie chart is exploded using the
explodeparameter value of thepie()method. Theexplodeparameter takes a list values of which each represents the wedge values from the center of the pie chart.
Without a shadow parameter
To differentiate between a pie chart having or not having a shadow, let us take a closer look at the output of the code below.
Code example
from matplotlib.pyplot import pie, showfrom numpy import arrayy = array([35, 25, 25, 15, 10])mylabels = ["Tomatoes", "Mangoes", "Oranges", "Apples", "Bamamas"]myexplode = [0.2, 0, 0.4, 0, 0]pie(y, labels = mylabels, explode = myexplode)show()
Code explanation
- Line 1: We import the library (
matplotlib) and module(pyplot). - 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 that represents theexplodeparameter of thepie()method. - Line 8: We use the
pie()method to create a pie chart with parameter valuesx,labels, andexplode. - Line 9: We use the
show()method to show our plot.
With a shadow parameter
We will create an exploded pie chart with shadows in the code below.
from matplotlib.pyplot import pie, showfrom numpy import arrayy = array([35, 25, 25, 15, 10])mylabels = ["Tomatoes", "Mangoes", "Oranges", "Apples", "Bamamas"]myexplode = [0.2, 0, 0.4, 0, 0]pie(y, labels = mylabels, explode = myexplode)show()
Code explanation
Like the first code, we created an exploded pie chart. But this time, we used the shadow parameter, which created a shadow on our pie chart, as can be seen in the code’s output.