Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to create a pie chart using Matplotlib

📅 2013-Oct-15 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ matplotlib, pie chart ⬩ 📚 Archive

[caption id="attachment_3932" align="aligncenter" width="392"][Pie chart created with Matplotlib](http://codeyarns.files.wordpress.com/2013/10/20131015-pie1.png) Pie chart created with Matplotlib[/caption]

Creating a pie chart is easy using Matplotlib. A simple pie chart can be created by passing the values representing each of the slices of the pie to the matplotlib.pyplot.pie method. For example:

#!/usr/bin/env python

import matplotlib.pyplot as pyplot

x_list = [1, 3, 6]
pyplot.pie(
        x_list
        )
pyplot.show()

Typically, you want some additions to the simple pie chart:

  1. The pie chart is oval by default. To make it a circle, call matplotlib.pyplot.axis("equal")

  2. To show labels of each pie slice, pass them as a list of strings to the labels parameter of the matplotlib.pyplot.pie method.

  3. To show the percentage of each pie slice, pass an output format to the autopct parameter of the matplotlib.pyplot.pie method.

  4. To display a title for the pie chart, call the matplotlib.pyplot.title method.

The pie chart shown above was created by these simple additions. The code is below:

#!/usr/bin/env python

import matplotlib.pyplot as pyplot

x_list = [1, 3, 6]
label_list = ["bells", "whistles", "pasta"]

pyplot.axis("equal")
pyplot.pie(
        x_list,
        labels=label_list,
        autopct="%1.1f%%"
        )
pyplot.title("Pastafarianism expenses")
pyplot.show()

Tried with: Matplotlib 1.3.0 and Ubuntu 12.04 LTS