Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot pie-chart with a single pie highlighted with Python Matplotlib?
Pie charts are one of the most popular visualization types for displaying percentages and proportions. In this tutorial, we'll learn how to create pie charts with highlighted segments using Python's Matplotlib library.
Basic Pie Chart Setup
First, let's install and import the required library ?
import matplotlib.pyplot as plt
# Sample data: Tennis Grand Slam titles
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
# Extract titles and player names
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
print("Titles:", titles)
print("Players:", players)
Titles: [20, 20, 17, 3] Players: ['Federer', 'Nadal', 'Djokovic', 'Murray']
Creating a Simple Pie Chart
Let's create a basic pie chart with percentage labels ?
import matplotlib.pyplot as plt
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
plt.pie(titles, labels=players, autopct='%1.1f%%')
plt.axis('equal') # Ensures the pie chart is circular
plt.title('Tennis Grand Slam Titles Distribution')
plt.show()
Highlighting Specific Pie Segments
To highlight specific segments, we use the explode parameter. This separates chosen wedges from the center ?
import matplotlib.pyplot as plt
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
# Highlight Djokovic's segment (index 2)
explode = (0, 0, 0.1, 0) # 0.1 separates Djokovic's wedge
plt.pie(titles, labels=players, explode=explode, autopct='%1.1f%%',
startangle=90, counterclock=False)
plt.axis('equal')
plt.title('Tennis Grand Slam Titles - Djokovic Highlighted')
plt.show()
Custom Value Display with Highlighting
Instead of percentages, we can display actual values using a custom formatting function ?
import matplotlib.pyplot as plt
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
# Calculate total and create value mapping
total = sum(titles)
values = {int(100 * title / total): title for title in titles}
def format_values(percent):
"""Custom function to display actual values instead of percentages"""
value = values.get(int(percent), int(percent * total / 100))
return f'{value}'
# Highlight multiple segments with different separation levels
explode = (0.1, 0.05, 0.2, 0) # Different highlight levels
plt.pie(titles, labels=players, explode=explode, autopct=format_values,
startangle=45, shadow=True)
plt.axis('equal')
plt.title('Tennis Grand Slam Titles - Multiple Highlights')
plt.show()
Advanced Highlighting with Colors
We can combine highlighting with custom colors for better visual impact ?
import matplotlib.pyplot as plt
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
# Custom colors with one highlighted segment
colors = ['lightblue', 'lightgreen', 'gold', 'lightcoral']
explode = (0, 0, 0.15, 0) # Highlight Djokovic
plt.pie(titles, labels=players, explode=explode, autopct='%1.1f%%',
colors=colors, shadow=True, startangle=90)
plt.axis('equal')
plt.title('Tennis Grand Slam Titles - Color Highlighted')
plt.show()
Complete Example
Here's a comprehensive example combining all the highlighting techniques ?
import matplotlib.pyplot as plt
# Data preparation
tennis_stats = (('Federer', 20), ('Nadal', 20), ('Djokovic', 17), ('Murray', 3))
titles = [title for player, title in tennis_stats]
players = [player for player, title in tennis_stats]
# Custom formatting function
total = sum(titles)
def format_display(percent):
value = int(percent * total / 100)
return f'{value}\n({percent:.1f}%)'
# Highlighting configuration
explode = (0.08, 0.08, 0.2, 0.05) # Emphasize Djokovic the most
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
# Create the highlighted pie chart
plt.figure(figsize=(10, 8))
wedges, texts, autotexts = plt.pie(titles, labels=players, explode=explode,
autopct=format_display, colors=colors,
shadow=True, startangle=45)
# Customize text properties
for autotext in autotexts:
autotext.set_color('black')
autotext.set_fontweight('bold')
plt.axis('equal')
plt.title('Tennis Grand Slam Titles Distribution\n(Highlighted Segments)',
fontsize=14, fontweight='bold')
plt.show()
Conclusion
Use the explode parameter to highlight specific pie segments by separating them from the center. Combine with custom colors and formatting functions for enhanced visual impact and clarity.
