Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to create a pie chart using Matplotlib

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

Pie chart created with Matplotlib

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧