How to Make Better Looking Matplotlib Pie Charts

2021-01-19 12:00:23 | #programming #python #dataviz

A pie chart consists of a pie where each slice represents its contribution to the whole pie. In this tutorial, we're going to introduce you to creating pie charts with Matplotlib, and customization options for making them more aesthetically pleasing.

If you're not familiar with Matplotlib, we recommend that you complete the prerequisits, which will introduce you to the Matplotlib Python framework, and line charts, and bar charts. If you need a crash course in Python, head over to the Python Developer section of our tutorials.

How to Set Up a Project Skeleton

How to Create Python Project Files with Windows 10 PowerShell 2.0+

cd ~
New-Item -ItemType "directory" -Path ".\matplotlib-bar-project"
cd matplotlib-bar-project
virtualenv venv
.\venv\Scripts\activate

To verify that the virtual environment is active, make sure (venv) is in the PowerShell command prompt. For example, (venv) PS C:\Users\username\matplotlib-bar-project>

How to Create Python Project Files with Linux Ubuntu 14.04+ or macOS

cd ~
mkdir matplotlib-bar-project
cd matplotlib-bar-project
virtualenv -p python3 venv
source venv/bin/activate

To verify that the virtual environment is active, make sure (venv) is in the terminal command prompt.

This will create the following files and folders, and activate the virtual environment.

▾ matplotlib-bar-project/
  ▸ venv/

Installing Matplotlib with Pip

This tutorial requires you to install a specific version of Matplotlib with pip3 install matplotlib==3.3.3. To get the plot to display in a window, you can install PyQt5 with pip3 install PyQt5==5.15.2.

We want to install a target version of these libraries because there may be API changes between the time this article is written to the time you read it.

How to Create a Pie Chart with Matplotlib

For our first task, we're going to generate a simple pie chart, using the plt.pie() method, and data derived from the popularity of programming languages.

C 30.5%
Java 19.1%
Python 17.4%
C++ 14.3
Other 18.7%
import matplotlib.pyplot as plt


# Data
labels = ['C', 'Java', 'Python', 'C++', 'Other']
values = [30.5, 19.1, 17.4, 14.3, 18.7]

# This will explode 'C' by .1
offset = (0.2, 0, 0, 0, 0)

plt.pie(values,
        labels=labels,
        radius=1,
        autopct="%1.1f%%",
        shadow=True,
        explode=offset,
        counterclock=False)


plt.savefig("plot.png")
plt.show()

Explanation of the Code

First, we import the necessary libraries(numpy and matplotlib)

Lines 5-6: We declare our labels and their values

Line 9: We emphasize C++ by exploding their slices.

Lines 11-17: We create our pie instance with the plt.pie() function.

pyplot.pie() Function Parameters Explained

plt.pie() accepts a variety of parameters, but we'll only cover the most relevant ones, for now.

plt.pie(
  x,
  explode=None,  labels=None, colors=None, 
  autopct=None, shadow=False, labeldistance=1.1,
  radius=None, counterclock=True, wedgeprops=None,
  **kwargs
)
Parameter Name Description Data Type Default Value
x Values for the wedge sizes array-like
explode An array with size equal to x, specifying the fraction to offset each wedge array-like
labels Labels of the slices list None
colors A sequence of matplotlib color args for the pie chart to cycle through array-like None
autopct Used to show the percentage of each slice in a pie chart None, string, or function None
pctdistance Ratio between the center of each slice and the beginning of the text generated by autopct float 0.6
shadow Used to give pie chart a 3D look by applying a drop shadow. To apply, set shadow=True. bool True
labeldistance The radial distance for which to draw the pie labels float or None 1.1
radius Used to show the percentage of each slice in a pie chart
counterclock Specify clockwise or counterclockwise fractions direction bool True
wedgeprops Arguments dict passed to the wedge objects. For instance, you can pass in wedgeprops = {'linewidth': 4} to set the width of the wedge border lines to 4. dict None

Resulting Pie Chart

The following depicts the default styling of a Matplotlib-generated pie chart. Notice the 90s drop shadow, bold colors that make text hard to read, and cramped text. We can do better.

Pie chart comparing the popularity of various programming languages

How to Customize a Matplotlib Pie Chart

How to Make a Donut Chart with Matplotlib

The following code switches to a lighter color palette, removes the drop shadow, and draws a circular cutout at the center of the chart.

import matplotlib.pyplot as plt


# Data
labels = ['C', 'Java', 'Python', 'C++', 'Other']
values = [30.5, 19.1, 17.4, 14.3, 18.7]

# This will explode every slice
offset = (0.1, 0.1, 0.1, 0.1, 0.1)

# Add colors
colors = ['#c4f8fe', '#ffadad', '#cafec4', '#fef4c4', '#d5c4fe', '#f7fec4']
fig1, ax = plt.subplots()

patches, texts, autotexts = ax.pie(values, radius=2.2, explode=offset, labels=labels, rotatelabels=True, colors=colors, autopct='%1.1f%%', shadow=False, startangle=180, counterclock=False)

for t in texts:
    t.set_color('grey')

for at in autotexts:
    at.set_color('grey')

# Donut
hole = plt.Circle((0, 0), 1.75, fc='white')
fig = plt.gcf()
fig.gca().add_artist(hole)

# Equal aspect ratio ensures that pie is drawn as a circle
ax.axis('equal')
plt.tight_layout()

plt.savefig("plot.png")
plt.show()

Donut chart comparing the popularity of various programming languages

How to Rotate the Labels and Values / Percentages of a Matplotlib Pie Chart

In this example, we go as far as to rotate all of the text to fit along the wedges.

import matplotlib.pyplot as plt


# Data
labels = ['C', 'Java', 'Python', 'C++', 'Other']
values = [30.5, 19.1, 17.4, 14.3, 18.7]

# This will explode every slice
offset = (0.1, 0.1, 0.1, 0.1, 0.1)

# Add colors
colors = ['#c4f8fe', '#ffadad', '#cafec4', '#fef4c4', '#d5c4fe', '#f7fec4']
fig1, ax = plt.subplots()

# pie, texts, autotexts = ax.pie(values, radius=2.2, explode=offset, labels=data, labeldistance=0.9, rotatelabels=True, colors=colors, autopct='%1.1f%%', shadow=False, startangle=180, counterclock=False)

patches, texts, autotexts = ax.pie(values, radius=2, colors=colors, startangle=180, labeldistance=0.9, labels=labels, rotatelabels=True, counterclock=False, autopct='%1.1f%%')

plt.setp(texts, rotation_mode="anchor", ha="center", va="center")
for t, at in zip(texts, autotexts):
    rot = t.get_rotation()
    t.set_rotation(rot + 90 + (1 - rot // 180) * 180)
    at.set_rotation(t.get_rotation())
    t.set_color('grey')
    at.set_color('grey')

# Donut
hole = plt.Circle((0, 0), 1.0, fc='white')
fig = plt.gcf()
fig.gca().add_artist(hole)


# Equal aspect ratio ensures that pie is drawn as a circle
ax.axis('equal')
plt.tight_layout()

plt.savefig("plot.png")
plt.show()

Donut chart comparing the popularity of various programming languages

Conclusion

In this tutorial, we learned about Matplotlib's customization options. We started with a pie chart generated with the default styling, made changes to the wedge colors, dropshadows, font colors, and even learned how to make a donut chart.

Book Recommendations for You

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Hire Us for IT and Consulting Services









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Services

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

We Noticed Adblock Running

Because we offer a variety of free programming tools and resources to our visitors, we rely on ad revenue to keep our servers up. Would you consider disabling Adblock for our site and clicking the "Refresh Page" button?

Contact