Python

How to Create Pie Charts with Matplotlib

How to Create Pie Charts with Matplotlib

Hey there! Today, I’m diving into one of the most popular (and delicious) tools for data visualization: the pie chart. Whether you’re a data newbie or a seasoned coder, pie charts are a fantastic way to represent proportions. Let’s walk through a basic example and then level it up with some practical enhancements. By the end, you’ll see how small tweaks can transform a simple chart into a polished, presentation-ready visual.

The Original Code A Simple Pie Chart

Let’s start with the basics. Here’s a minimal example using Python’s matplotlib:

import matplotlib.pyplot as plt

sizes = [40, 30, 20, 10]
labels = ['A', 'B', 'C', 'D']

plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()

Breaking It Down

  1. Libraries: We import matplotlib.pyplot (aliased as plt), the go-to library for plotting. While numpy is imported here, it’s not actually used in this snippet—it’s often included for numerical workflows.
  2. Data:
    • sizes: A list of values representing each slice’s proportion (here, percentages).
    • labels: Text labels for each slice.
  3. Plotting:
    • plt.pie() generates the chart. The autopct parameter formats percentage labels (one decimal place).
    • plt.show() displays the chart.

This code works, but the result is pretty vanilla. Let’s jazz it up!

A Sleeker, More Informative Pie Chart

Here’s the upgraded version with practical improvements:

import matplotlib.pyplot as plt

sizes = [40, 30, 20, 10]
labels = ['A', 'B', 'C', 'D']
explode = [0.1, 0, 0, 0]  # "Pop out" the first slice

plt.figure(figsize=(8, 8))  # Larger figure size

plt.pie(
    sizes,
    labels=labels,
    autopct='%1.1f%%',
    explode=explode,  # Highlight a slice
    startangle=90,    # Rotate chart for better orientation
    shadow=True       # Add depth with a shadow
)

plt.axis('equal')     # Ensure the pie is a circle
plt.title("Enhanced Pie Chart")  
plt.legend(labels, title="Categories", loc="upper right")  
plt.savefig("enhanced_pie_chart.png")  # Save as image
plt.show()

What’s New? Key Enhancements Explained

Let’s unpack the upgrades:

  1. Exploding a Slice
    • explode = [0.1, 0, 0, 0] shifts the first slice outward by 10% of the radius. This draws attention to a specific category (like highlighting top revenue sources).
  2. Custom Start Angle
    • startangle=90 rotates the chart so the first slice starts at the top (12 o’clock position). This avoids awkward orientations, like starting a dominant slice halfway off-screen.
  3. Shadow Effect
    • shadow=True adds a subtle 3D-like drop shadow, making the chart visually appealing.
  4. Title and Legend
    • A title (plt.title()) clarifies the chart’s purpose.
    • The legend (plt.legend()) maps labels to colors, which is especially helpful if slice labels are truncated or overlapping.
  5. Saving the Figure
    • plt.savefig() exports the chart as a PNG (or other formats) for use in reports or slides.
  6. Equal Aspect Ratio
    • plt.axis('equal') ensures the pie isn’t distorted into an ellipse—a common pitfall when resizing figures.

Why Do These Tweaks Matter?

  • Clarity: Labels, legends, and titles make the chart self-explanatory.
  • Focus: Exploding a slice directs viewers to key data points.
  • Professionalism: Shadows and proper sizing ensure the chart looks polished in presentations.

Final Thought

A pie chart is more than just a circle divided into slices—it’s a storytelling tool. While the basic version gets the job done, thoughtful enhancements turn it into a communication powerhouse. By adding context (titles, legends), improving readability (exploding slices), and embracing aesthetics (shadows, angles), your charts will not only inform but also engage your audience.

author-avatar

About Daniyal Ahmed

Python Developer since 2020 | Release Manager for Python 3.8 | Creator of Black code formatter | Contributing to Python's growth and adoption.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments