Trusted answers to developer questions

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

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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 the True value.

The wedge of the pie chart is exploded using the explode parameter value of the pie() method. The explode parameter 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, show
from numpy import array
y = 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 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 that 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.
  • 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, show
from numpy import array
y = 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.

RELATED TAGS

matplotlib
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?