Pie charts might not be the most advanced data visualization tool, but they serve a simple purpose: to show proportions at a glance. Whether you’re analyzing sales figures, poll results, or survey outcomes, a clean pie chart communicates the point effectively. In Python, the Matplotlib library makes it straightforward to generate and customize these charts to suit your needs.
Matplotlib, one of the most stable plotting libraries in Python, offers a simple function called pie()
to draw pie charts. Before diving into code, ensure Matplotlib is installed:
pip install matplotlib
Here’s how to create a basic pie chart:
import matplotlib.pyplot as plt
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [30, 25, 25, 20]
plt.pie(sizes, labels=labels)
plt.title('Fruit Sales Distribution')
plt.show()
This generates a default pie chart with labeled slices. For added clarity, you can display percentages directly on the chart:
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
The autopct
parameter formats the percentages to one decimal place, ensuring quick readability.
Once you have a basic chart, you can customize its appearance for clarity and emphasis. Use the colors
parameter to change slice colors:
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
To highlight a specific slice, such as emphasizing ‘Apples’, use the explode
parameter:
explode = (0.1, 0, 0, 0) # Emphasize the first slice
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%')
Adding a shadow or adjusting the start angle can also enhance readability:
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, shadow=True)
For a donut-style chart, add a circle at the center:
wedges, texts, autotexts = plt.pie(sizes, labels=labels, autopct='%1.1f%%')
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
Pie charts are often generated from datasets rather than hardcoded values. Using Pandas, you can create a pie chart from a dataset:
import pandas as pd
data = {
'Fruit': ['Apples', 'Bananas', 'Cherries', 'Dates'],
'Sales': [300, 250, 250, 200]
}
df = pd.DataFrame(data)
plt.pie(df['Sales'], labels=df['Fruit'], autopct='%1.1f%%')
plt.title('Sales Distribution by Fruit')
plt.show()
For integration into dashboards or automated reports, save your chart instead of displaying it:
plt.savefig('pie_chart.png')
When creating data visualizations, selecting the right chart type is crucial. Pie charts are excellent for simple breakdowns with a few categories, but as segments increase, readability declines. In such cases, bar charts offer better clarity. For trends over time, line charts provide more insight. While Matplotlib’s pie chart capabilities are robust, sometimes switching to a bar or line chart enhances clarity.
Pie charts are not about showing everything—they’re about emphasizing the essentials. When applied effectively, they bring out stories that might be buried in a table or lost in a bar chart. With Matplotlib, crafting a Python pie chart is quick and doesn’t compromise on style or readability. Whether it’s a report, business review, or dashboard summary, a well-placed pie chart delivers your message cleanly. Keep it simple, keep it readable, and let the proportions do the talking. That’s the power of effective data visualization.
Discover the essential differences between class and instance attributes in Python. Learn how each operates, when to apply them, and their impact on Python classes.
Ready to dive into Python? This guide covers the core concepts you need to understand, helpful resources, and project ideas to start using Python effectively. Perfect for both beginners and those brushing up.
Discover how to effectively utilize Delta Lake for managing data tables with ACID transactions and a reliable transaction log with this beginner's guide.
Discover a clear SQL and PL/SQL comparison to understand how these two database languages differ and complement each other. Learn when to use each effectively.
Discover how cloud analytics streamlines data analysis, enhances decision-making, and provides global access to insights without the need for extensive infrastructure.
Discover the most crucial PySpark functions with practical examples to streamline your big data projects. This guide covers the key PySpark functions every beginner should master.
Discover the essential role of databases in managing and organizing data efficiently, ensuring it remains accessible and secure.
How product quantization improves nearest neighbor search by enabling fast, memory-efficient, and accurate retrieval in high-dimensional datasets.
How ETL and workflow orchestration tools work together to streamline data operations. Discover how to build dependable processes using the right approach to data pipeline automation.
How Amazon S3 works, its storage classes, features, and benefits. Discover why this cloud storage solution is trusted for secure, scalable data management.
Explore what loss functions are, their importance in machine learning, and how they help models make better predictions. A beginner-friendly explanation with examples and insights.
Explore what data warehousing is and how it helps organizations store and analyze information efficiently. Understand the role of a central repository in streamlining decisions.
Discover how predictive analytics works through its six practical steps, from defining objectives to deploying a predictive model. This guide breaks down the process to help you understand how data turns into meaningful predictions.
Explore the most common Python coding interview questions on DataFrame and zip() with clear explanations. Prepare for your next interview with these practical and easy-to-understand examples.