Nested pie charts in Matplotlib

Matplotlib is a Python library best used for visualizing various forms of data. This library contains a vast set of charts to achieve this purpose including pie charts. Aside from the traditional pie chart, we can use Matplotlib to go a step further and create nested pie charts to accurately demonstrate subdivisions. In this Answer, we'll look at implementing nested pie charts in Matplotlib.

Pie charts

Pie charts are an excellent way to represent data pictorially. They are perhaps one of the most straightforward and self-explanatory data visualization techniques.

Various definitions

  1. Formally speaking, a pie chart, also called a circle chart, is a circular entity or a pie where different slices of the pie represent the division of data.

  2. Simply put, different portions of the circle show different sections of our data.

A simple piechart
A simple piechart

Basics of pie charts in matplotlib

Matplotlib is a great data visualization library and has a built-in method called using .pie to create pie charts.

Note: Learn more about basic pie charts here.

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
dataset = np.array([[20., 42.], [64., 92.], [34., 56.]])
colorset = plt.colormaps["Dark2"]
colors = colorset([0, 4, 8])
ax.pie(dataset.sum(axis=1), colors=colors)
ax.set(aspect='equal', title='Simple Pie Chart')
plt.show()
Simple pie chart using Python's matplotlib
Simple pie chart using Python's matplotlib

Nested pie charts

When we have to show data within the central pie slices too, we choose the nestedstored within another entity pie chart approach that depicts the different levels of data as concentric circles within the pie. Therefore, we can successfully show multiple series in a single pie.

Further divisions within a pie chart
Further divisions within a pie chart

Have you gotten the hang of nested pie charts?

Question

Can the subcategories be larger than the main categories?

Show Answer
Concise difference in simple and nested pie charts

Code sample

Let's now implement our understanding of nested pie charts using matplotlib. The basics remain the same, we just have to add an inner circle in this version.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

size = 0.5

dataset = np.array([[20., 42.], [64., 92.], [34., 56.]]) 

colorset = plt.colormaps["Dark2"]
outer = colorset([0, 4, 8])

inner = colorset([1, 2, 3, 5, 6, 7, 9, 10, 11])

ax.pie(dataset.sum(axis=1), radius=1, colors=outer, wedgeprops=dict(width=size, edgecolor='w'))

ax.pie(dataset.flatten(), radius=1-size, colors=inner, wedgeprops=dict(width=size, edgecolor='w'))

ax.set(aspect='equal', title='Nested Pie Chart') 

plt.show()

Code explanation

  • Lines 1–2: Prior to writing our main code, we first import matplotlib.pyplot with an alias name of plt for plotting. We then import numpy with an alias name of np for numerical operations.

  • Line 4: First, we use plt.subplots() to generate a figure and an axis object, and assign them fig and ax variables respectively.

  • Line 6: The size is then set to 0.5, which represents the width of the wedge in the pie chart.

  • Line 8: We create a numpy array, i.e., dataset, and assign 2D array values to it.

  • Line 10: For our aesthetics regarding the piechart, we use the color Dark2 set from colormaps and assign it to the colorset variable.

  • Line 11: We take the color shades depicted by [0, 4, 8] from our chosen color palette for our outer main categories and assign it to outer.

  • Line 13: Moving towards our inner circle now, we specify the color shades corresponding to [1, 2, 3, 5, 6, 7, 9, 10, 11] from the colorset for the inner pie and assign it to inner.

  • and set it on the inner variable.

  • Line 15: We call the ax.pie function to create the outer pie chart and pass the sum of values along each row of the dataset, radius i.e., 1, colors i.e., outer, and the wedge properties wedgeprops i.e., width and edgecolor as parameters.

  • Line 17: We then use ax.pie function to create the inner pie chart and pass the flattened dataset values, radius i.e., 1 - size, colors i.e., inner, and the wedge properties wedgeprops i.e., width and edgecolor as parameters.

  • Line 19: Next, we use the ax.set function and pass the aspect ratio of the plot i.e., equal, and the title for the plot, i.e., "Nested Pie Chart" as parameters to set them respectively.

  • Line 21: Lastly, we call plt.show() to display our well-made pie chart!

Note: The dataset for the pie chart can be changed to reflect real life data and display the actual strength of pie charts.

Chart output

Nested pie chart using Python's matplotlib
Nested pie chart using Python's matplotlib

Note: Matplotlib supports quite a few aesthetic color combinations in its colormaps. For instance, tab20c, twilight, and many more. These can be replaced with Dark2.

Alternate code sample

The pie charts do not have to be as simple as the one we've made above. Once you've gotten the hang of it, feel free to add styles and other details as you like!

In the following example, we've changed the colormap, added labels for our data, and displayed it using a legend.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

size = 0.3

dataset = np.array([[20., 42.], [64., 92.], [34., 56.]]) 

colorset = plt.colormaps["Pastel1"]
outer_colors = colorset([0, 4, 8])

inner_colors = colorset([1, 2, 3, 5, 6, 7, 9, 10, 11])

outer_pie = ax.pie(dataset.sum(axis=1), radius=1, colors=outer_colors, wedgeprops=dict(width=size, edgecolor='w'), labels=['Category A', 'Category B', 'Category C'])

inner_pie = ax.pie(dataset.flatten(), radius=1-size, colors=inner_colors, wedgeprops=dict(width=size, edgecolor='w'))

ax.legend(outer_pie[0], ['Category A', 'Category B', 'Category C'], loc='upper left', title='Outer Categories')
ax.legend(inner_pie[0], ['Subcategory 1', 'Subcategory 2', 'Subcategory 3', 'Subcategory 4', 'Subcategory 5', 'Subcategory 6', 'Subcategory 7', 'Subcategory 8', 'Subcategory 9'][:len(dataset.flatten())], loc='upper right', title='Inner Subcategories')

ax.set(aspect='equal', title='Nested Pie Chart')

plt.show()

Alternate chart output

Use cases of nested pie charts

  1. Nested pie charts are used to visualize hierarchical data with multiple levels of categories and subcategories.

  2. We can use them to help show the proportion of each subcategory within the parent category.

  3. Nested pie charts allow us to compare the distribution of subcategories across different categories easily.

  4. They are primarily used in business, finance, and marketing to analyze hierarchical data relationships.

  5. These strengths allow nested pie charts to aid in decision-making as well.

Keywords used in matplotlib's pie charts

Properties

Explanation

radius

Specifies the radius of the pie chart

colors

Defines the color scheme for the slices of the pie

wedgeprops

Sets the properties for the wedges, like width or edge color

labels

Indicates the category names

startangle

Determines the starting angle of the first pie chart's slice

shadow

Adds a shadow effect to the pie chart

legend

Displays a legend to show the categories of the pie chart

title

Gives a title / heading to the pie chart

aspect

Ensures that the pie chart is a circle, and maintains the aspect ratio

Congratulations, you can now make nested pie charts in Python using matplotlib!

Let’s test ourselves on matplotlib’s pie charts!

Question

Why are the inner colors of the subcategories usually kept different from the outer category, even if they belong to the same common parent?

Show Answer

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved