0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Create Donut Chart in Matplotlib: Simple Guide

To create a donut chart in matplotlib, use the pie() function with the wedgeprops parameter setting width less than 1 to create the hole. This makes the pie chart look like a donut by cutting out the center.
๐Ÿ“

Syntax

The basic syntax to create a donut chart uses plt.pie() with wedgeprops={'width': value}. The width controls the thickness of the donut ring. Values closer to 1 make a thicker ring, and values closer to 0 make a thinner ring.

  • sizes: List of values for each slice.
  • labels: List of labels for slices.
  • wedgeprops: Dictionary to style wedges; {'width': 0.3} creates the donut hole.
  • startangle: Rotates the start of the chart for better view.
python
plt.pie(sizes, labels=labels, wedgeprops={'width': 0.3}, startangle=90)
๐Ÿ’ป

Example

This example shows how to create a simple donut chart with 4 categories. It uses plt.pie() with wedgeprops to create the hole in the center.

python
import matplotlib.pyplot as plt

sizes = [25, 35, 20, 20]
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']

plt.pie(sizes, labels=labels, wedgeprops={'width': 0.4}, startangle=90, autopct='%1.1f%%')
plt.title('Fruit Distribution Donut Chart')
plt.show()
Output
A donut chart with four colored slices labeled Apples, Bananas, Cherries, and Dates, showing percentage values inside each slice and a hole in the center.
โš ๏ธ

Common Pitfalls

Common mistakes when creating donut charts include:

  • Not setting wedgeprops={'width': value}, which results in a normal pie chart without a hole.
  • Using a width value too close to 0, making the ring very thin and hard to see.
  • Forgetting to set startangle for better slice orientation.
  • Not using autopct to show percentages, which can make the chart less informative.
python
import matplotlib.pyplot as plt

sizes = [30, 40, 30]
labels = ['A', 'B', 'C']

# Wrong: No wedgeprops, no hole
plt.pie(sizes, labels=labels)
plt.title('Normal Pie Chart')
plt.show()

# Right: With wedgeprops for donut
plt.pie(sizes, labels=labels, wedgeprops={'width': 0.5}, startangle=90, autopct='%1.1f%%')
plt.title('Donut Chart')
plt.show()
Output
First plot: normal pie chart without hole. Second plot: donut chart with hole and percentages.
๐Ÿ“Š

Quick Reference

Tips for creating donut charts in Matplotlib:

  • Use wedgeprops={'width': 0.3} to create the donut hole.
  • Set startangle=90 to rotate the chart for better slice alignment.
  • Use autopct='%1.1f%%' to display percentages on slices.
  • Customize colors with colors parameter if needed.
โœ…

Key Takeaways

Create a donut chart by setting wedgeprops={'width': value} in plt.pie().
Choose a width between 0 and 1 to control the donut ring thickness.
Use startangle=90 to rotate the chart for better visual appeal.
Add autopct='%1.1f%%' to show percentage labels on slices.
Without wedgeprops, plt.pie() creates a normal pie chart, not a donut.