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.
Learn how to train static embedding models up to 400x faster using Sentence Transformers. Explore how contrastive learning and smart sampling techniques can accelerate embedding generation and improve accuracy.
Discover how SmolVLM is revolutionizing AI with its compact 250M and 500M vision-language models. Experience strong performance without the need for hefty compute power.
Discover CFM’s innovative approach to fine-tuning small AI models using insights from large language models (LLMs). A case study in improving speed, accuracy, and cost-efficiency in AI optimization.
Discover the transformative influence of AI-powered TL;DR tools on how we manage, summarize, and digest information faster and more efficiently.
Explore how the integration of vision transforms SmolAgents from mere scripted tools to adaptable systems that interact with real-world environments intelligently.
Explore the lightweight yet powerful SmolVLM, a distinctive vision-language model built for real-world applications. Uncover how it balances exceptional performance with efficiency.
Delve into smolagents, a streamlined Python library that simplifies AI agent creation. Understand how it aids developers in constructing intelligent, modular systems with minimal setup.
Discover everything about DataRobot - from its AI capabilities and logo evolution to pricing models and enterprise use cases.
Discover how DataRobot GenAI's intelligent automation solves enterprise challenges with AI-powered data processing, predictive insights, and scalable workflows.
Google DeepMind's AlphaEvolve combines Gemini LLMs with evolutionary algorithms to autonomously discover novel mathematical solutions and optimize critical infrastructure, achieving breakthroughs like 56-year-old matrix multiplication records.
Claude 4 sets new benchmarks in AI coding with 7-hour continuous programming sessions and 24-hour Pokémon gameplay capabilities, now powering GitHub Copilot.
Discover how ChatGPT can assist with resume writing, job search strategy, LinkedIn profile optimization, interview preparation, and career development to help you land your dream job.