bhylu.com

Advertisements

Matplotlib Pie Charts

A pie chart shows parts of one whole when categories are mutually exclusive and the total has a clear meaning. A bar chart is usually easier for close comparisons.

Understand the idea

Use only a few non-negative parts and state what the whole represents. Percent labels show a share of the supplied total, not a percentage of some unstated population. Equal aspect keeps the circle undistorted. Avoid three-dimensional effects or exploded slices that overemphasise one group without a reason.

Where to try it

Run this complete script in a local virtual environment with Matplotlib installed (py -m pip install matplotlib). It uses a non-interactive backend and saves workshop.png in the current folder. The site shows a rendered example below; its text-only online runner does not display plot windows.

A worked example

Python

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.pie([12, 8, 5], labels=["HTML", "CSS", "Python"], autopct="%1.0f%%")
ax.set(title="Share of 25 demo registrations", aspect="equal")
fig.savefig("workshop.png", dpi=140)
plt.close(fig)
print("Saved workshop.png")

Read the result

The shares are 48%, 32%, and 20% of the stated total of 25 registrations.

The shares are 48%, 32%, and 20% of the stated total of 25 registrations.
Rendered from this original example. Change and rerun the script locally to make your own chart.

Try one change

Draw the same values as bars and decide which version makes the comparison easier.

For package options, see the Matplotlib documentation.