Donut Chart using Matplotlib in Python


A Donut chart is a circular chart that shows the relative representation of the data in a circular way. Donut and pie charts look similar but the donut chart has a hole in the center of the chart whereas the pie chart doesn’t. A donut chart can be created for a dataset containing various groups in different proportions using Matplotlib. In this article, we will create a Donut chart using Matplotlib.

Algorithm

The donut chart in Matplotlib can be drawn using the methods provided by the matplotlib library. We can follow the below algorithm to make a Donut chart in Matplotlib.

  • Import the necessary libraries, including Matplotlib.

  • Define the data you want to plot, including the labels and sizes.

  • Create a figure and an axis object using plt.subplots().

  • Set the aspect ratio of the plot to equal using the subplot_kw parameter of plt.subplots().

  • Set the start angle for the plot using the startangle parameter of ax.pie().

  • Create the donut chart using ax.pie(), passing in the sizes as the data and the labels as the labels parameter.

  • Customize the chart by adding an inner circle using plt.Circle(), adding a legend using ax.legend(), changing the font size and weight using plt.setp(), and setting the chart title using ax.set_title().

  • Display the chart using plt.show().

Installing Matplotlib

Matplotlib is a data visualization library in Python that allows you to create a wide range of charts. To install you can type the following command on your command line or terminal.

Pip install matplotlib

Creating Dummy Data

To create a donut chart we need dummy data that can be visualized using matplotlib in Python. We create a label list and a sizes list that contains the relative sizes of each label category.

labels = ['Apples', 'Bananas', 'Grapes', 'Oranges']
sizes = [25, 30, 15, 30]

Creating Basic Donut Chart

We will use the plt.pie() function to create the donut chart. This function takes the sizes list as arguments and creates a donut chart representing each category.

Syntax

plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, normalize=None, *, data=None)

The Parameters passed to the plt.pie() function are have their specific significance which is explained below −

  • x − The data to be plotted in the form of a sequence of values.

  • explode − A sequence of values specifying the fraction of the radius with which to offset each wedge.

  • labels − A sequence of strings to be used as labels for each wedge.

  • colors − A sequence of colors to be used for each wedge.

  • autopct − A format string used to format the percentage text labels. If None, no labels will be displayed.

  • pctdistance − The distance from the center of the pie chart to draw the percentage labels.

  • shadow − A boolean value indicating whether or not to draw a shadow beneath the pie chart.

  • startangle − The angle at which to start drawing the first wedge, in degrees.

  • radius − The radius of the pie chart. If None, the radius is set to 1.

  • counterclock − A boolean value indicating whether to draw the wedges counterclockwise or clockwise.

  • wedgeprops − A dictionary of keyword arguments to be passed to the Wedge class used to create each wedge.

  • textprops − A dictionary of keyword arguments to be passed to the Text class used to create the text labels.

  • center − The center of the pie chart, as a tuple of (x, y) coordinates.

  • frame − A boolean value indicating whether or not to draw a frame around the pie chart.

  • rotatelabels − A boolean value indicating whether or not to rotate the text labels.

  • normalize − A boolean value indicating whether to normalize the data to 100% before plotting.

Example

In the below example we are using the labels and the sizes list to create a donut chart representing each label category. We first create a figure and axis object using the plt.subplots() function. We set the aspect ratio of the axis to "equal" to ensure that the chart is circular. We then use the ax.pie() function to create a pie chart with a wedge width of 0.5 and a starting angle of -40.

# Data
import matplotlib.pyplot as plt
labels = ['Apples', 'Bananas', 'Grapes', 'Oranges']
sizes = [25, 30, 15, 30]

# Plot
fig, ax = plt.subplots(figsize=(10, 6), subplot_kw=dict(aspect="equal"))

wedges, texts = ax.pie(sizes, wedgeprops=dict(width=0.5), startangle=-40)

# Inner circle
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Add labels
ax.legend(wedges, labels,
      title="Fruits",
      loc="center left",
      bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(texts, size=12, weight="bold")

ax.set_title("Fruit Distribution")

plt.show()

Output

Customizing the Donut Chart

We can customize the donut chart further by changing the color for representation in the chart, font changes, axis label changes, etc.

Example

To change the color of the chart we can pass a list of colors to the wedge props parameter of the ax.pie function. In the below example, we will change our previous donut chart color to red, green, blue, and orange.

import matplotlib.pyplot as plt
# Data
labels = ['Apples', 'Bananas', 'Grapes', 'Oranges']
sizes = [25, 30, 15, 30]
colors = ['red', 'green', 'blue', 'orange']

# Plot
fig, ax = plt.subplots(figsize=(10, 6), subplot_kw=dict(aspect="equal"))

wedges, texts = ax.pie(sizes, wedgeprops=dict(width=0.5, edgecolor='w'), startangle=-40, colors=colors)

# Inner circle
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Add labels
ax.legend(wedges, labels,
      title="Fruits",
      loc="center left",
      bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(texts, size=12, weight="bold")

ax.set_title("Fruit Distribution")

plt.show()

Output

Conclusion

In this article, we discussed how we can create a donut chart representation of any data using matplotlib and what is the basic difference between a donut chart and a pie chart. Matplotlib is a data visualization library that is used to show the data in the form of various charts. The donut chart can also be customized according to specific data visualization needs.

Updated on: 10-Jul-2023

847 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements