Nested Pie Charts With Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Pie charts are popular data visualization tools used to represent data in a circular form. However, there are times when you might want to create a nested version of the pie chart, known as the donut chart. This tutorial will guide you through creating nested pie charts using Matplotlib, a popular data visualization library in Python.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("`Saving Figures to File`") matplotlib/PlottingDataGroup -.-> matplotlib/bar_charts("`Bar Charts`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/pie_charts("`Pie Charts`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/with_statement -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} matplotlib/figures_axes -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} matplotlib/saving_figures -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} matplotlib/bar_charts -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} matplotlib/pie_charts -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/variables_data_types -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/lists -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/tuples -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/importing_modules -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/data_collections -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/numerical_computing -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/data_visualization -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} python/build_in_functions -.-> lab-48847{{"`Nested Pie Charts With Matplotlib`"}} end

Import necessary libraries

First, we need to import the necessary libraries. In this case, we need Matplotlib and numpy.

import matplotlib.pyplot as plt
import numpy as np

Create a nested pie chart using ax.pie

We can create a nested pie chart using ax.pie method. We will first generate some fake data, corresponding to three groups. In the inner circle, we'll treat each number as belonging to its own group. In the outer circle, we'll plot them as members of their original 3 groups.

fig, ax = plt.subplots()

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

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

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

ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()

Create a nested pie chart using ax.bar

We can also create a nested pie chart using ax.bar method on axes with a polar coordinate system. This may give more flexibility on the exact design of the plot.

fig, ax = plt.subplots(subplot_kw=dict(projection="polar"))

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
## Normalize vals to 2 pi
valsnorm = vals/np.sum(vals)*2*np.pi
## Obtain the ordinates of the bar edges
valsleft = np.cumsum(np.append(0, valsnorm.flatten()[:-1])).reshape(vals.shape)

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

ax.bar(x=valsleft[:, 0],
       width=valsnorm.sum(axis=1), bottom=1-size, height=size,
       color=outer_colors, edgecolor='w', linewidth=1, align="edge")

ax.bar(x=valsleft.flatten(),
       width=valsnorm.flatten(), bottom=1-2*size, height=size,
       color=inner_colors, edgecolor='w', linewidth=1, align="edge")

ax.set(title="Pie plot with `ax.bar` and polar coordinates")
ax.set_axis_off()
plt.show()

Customize the Nested Pie Chart

We can customize the nested pie chart by changing the colors, adding labels, and adjusting the size.

fig, ax = plt.subplots()

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

## Add labels
labels = ['Group 1', 'Group 2', 'Group 3']
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
       wedgeprops=dict(width=size, edgecolor='w'), labels=labels, labeldistance=0.7)

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

## Set the title
ax.set(aspect="equal", title='Nested Pie Chart')

plt.show()

Save the Nested Pie Chart

We can save the nested pie chart as an image in png, pdf, or svg format.

fig.savefig('nested_pie_chart.png', dpi=300, bbox_inches='tight')

Summary

In this tutorial, we have learned how to create nested pie charts in Matplotlib using two methods: ax.pie and ax.bar. We have also learned how to customize the nested pie chart by adding labels, changing colors, and adjusting the size. Finally, we have seen how to save the nested pie chart as an image in png, pdf, or svg format.

Other Python Tutorials you may like