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
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.
Simply put, different portions of the circle show different sections of our data.
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 pltimport numpy as npfig, 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()
Nested pie charts
When we have to show data within the central pie slices too, we choose the
Can the subcategories be larger than the main categories?
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.pyplotwith an alias name ofpltfor plotting. We then importnumpywith an alias name ofnpfor numerical operations.Line 4: First, we use
plt.subplots()to generate a figure and an axis object, and assign themfigandaxvariables 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
colormapsand assign it to thecolorset 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 toouter.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 thecolorsetfor the inner pie and assign it toinner.and set it on the inner variable.
Line 15: We call the
ax.piefunction to create the outer pie chart and pass the sum of values along each row of the dataset,radiusi.e., 1,colorsi.e., outer, and the wedge propertieswedgepropsi.e.,widthandedgecoloras parameters.Line 17: We then use
ax.piefunction to create the inner pie chart and pass the flattened dataset values,radiusi.e., 1 - size,colorsi.e., inner, and the wedge propertieswedgepropsi.e.,widthandedgecoloras parameters.Line 19: Next, we use the
ax.setfunction and pass theaspectratio of the plot i.e., equal, and thetitlefor 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
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
Nested pie charts are used to visualize hierarchical data with multiple levels of categories and subcategories.
We can use them to help show the proportion of each subcategory within the parent category.
Nested pie charts allow us to compare the distribution of subcategories across different categories easily.
They are primarily used in business, finance, and marketing to analyze hierarchical data relationships.
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!
Why are the inner colors of the subcategories usually kept different from the outer category, even if they belong to the same common parent?
Free Resources