Python Tutorials · Python Matplotlib

Matplotlib Pie Charts

Learn all about Matplotlib Pie Charts in this comprehensive tutorial.

5 min read intermediate
  • With Pyplot, you can use the pie() function to draw pie charts:
  • Add labels to the pie chart with the labels parameter.
  • As mentioned the default start angle is at the x-axis, but you can change the start angle by specifying a startangle parameter.
  • Maybe you want one of the wedges to stand out?
  • Add a shadow to the pie chart by setting the shadows parameter to True:
  • You can set the color of each wedge with the colors parameter.
  • To add a list of explanation for each wedge, use the legend() function:

Creating Pie Charts

With Pyplot, you can use the pie() function to draw pie charts:

python

As you can see the pie chart draws one piece (called a wedge) for each value in the array (in this case [35, 25, 25, 15]).

By default the plotting of the first wedge starts from the x-axis and moves counterclockwise:

Note: Note: The size of each wedge is determined by comparing the value with all the other values, by using this formula: The value divided by the sum of all values: x/sum(x)

Labels

Add labels to the pie chart with the labels parameter.

The labels parameter must be an array with one label for each wedge:

python

Start Angle

As mentioned the default start angle is at the x-axis, but you can change the start angle by specifying a startangle parameter.

The startangle parameter is defined with an angle in degrees, default angle is 0:

python

Explode

Maybe you want one of the wedges to stand out? The explode parameter allows you to do that.

The explode parameter, if specified, and not None, must be an array with one value for each wedge.

Each value represents how far from the center each wedge is displayed:

python

Shadow

Add a shadow to the pie chart by setting the shadows parameter to True:

python

Colors

You can set the color of each wedge with the colors parameter.

The colors parameter, if specified, must be an array with one value for each wedge:

python

You can use Hexadecimal color values, any of the 140 supported color names, or one of these shortcuts:

'r' - Red 'g' - Green 'b' - Blue 'c' - Cyan 'm' - Magenta 'y' - Yellow 'k' - Black 'w' - White

Legend

To add a list of explanation for each wedge, use the legend() function:

python

To add a header to the legend, add the title parameter to the legend function.

python

Module quiz

2 questions
1

Which of the following is true about Matplotlib Pie Charts?

2

What is the most common pitfall when working with Matplotlib Pie Charts?

Answer all questions to submit.