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
Selected Reading
How to plot a nested pie chart in Matplotlib?
A nested pie chart displays hierarchical data with an outer ring representing main categories and an inner ring showing subcategories. Matplotlib's pie() function can create concentric pie charts by adjusting the radius and width parameters.
Creating a Basic Nested Pie Chart
Here's how to create a nested pie chart with outer and inner rings ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [8, 6]
plt.rcParams["figure.autolayout"] = True
# Create figure and subplot
fig, ax = plt.subplots()
# Define data and styling
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])
# Create outer pie chart
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
# Create inner pie chart
ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
plt.title('Nested Pie Chart')
plt.show()
Enhanced Nested Pie Chart with Labels
Adding labels and percentages makes the chart more informative ?
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(10, 8))
# Data for nested pie chart
categories = ['Category A', 'Category B', 'Category C']
subcategories = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']
vals = np.array([[45, 25], [30, 35], [20, 15]])
# Colors
outer_colors = ['#ff9999', '#66b3ff', '#99ff99']
inner_colors = ['#ffcccc', '#ff6666', '#cce6ff', '#3399ff',
'#ccffcc', '#66ff66']
# Outer ring (main categories)
wedges1, texts1, autotexts1 = ax.pie(vals.sum(axis=1),
radius=1,
colors=outer_colors,
labels=categories,
autopct='%1.1f%%',
wedgeprops=dict(width=0.4, edgecolor='white'))
# Inner ring (subcategories)
wedges2, texts2, autotexts2 = ax.pie(vals.flatten(),
radius=0.6,
colors=inner_colors,
labels=subcategories,
autopct='%1.1f%%',
wedgeprops=dict(width=0.4, edgecolor='white'))
plt.title('Enhanced Nested Pie Chart with Labels', fontsize=16, pad=20)
plt.show()
Key Parameters
| Parameter | Description | Effect |
|---|---|---|
radius |
Distance from center | Controls ring position |
width |
Ring thickness | Creates donut effect |
edgecolor |
Border color | Separates segments |
Conclusion
Nested pie charts are created by plotting two pie charts with different radii and widths. The outer ring represents main categories while the inner ring shows subcategories, making hierarchical data visualization clear and intuitive.
Advertisements
