Matplotlib Pie Charts

A pie chart is a circular statistical graphic that is divided into slices to illustrate numerical proportions. Each slice represents a category's contribution to the whole. Pie charts are particularly useful when you want to show the relative sizes of parts of a whole.

Creating a Basic Pie Chart

To create a basic pie chart, use the plt.pie() function from the Matplotlib library:

Python
import matplotlib.pyplot as plt

labels = ["A", "B", "C", "D"]
sizes = [15, 30, 45, 10]

plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=140)
plt.show()

In this example:

This code produces a simple pie chart with four slices, each labeled and annotated with its percentage of the whole.

Exploding Slices

You can "explode" a slice to highlight it, drawing attention to a particular category:

Python
explode = (0, 0.1, 0, 0)  # "explode" the 2nd slice

plt.pie(sizes, explode=explode, labels=labels, autopct="%1.1f%%", startangle=140)
plt.show()

In this example, the second slice (B) is "exploded" or pulled out from the pie chart slightly, making it stand out from the others.

Customizing Colors

Colors can be customized to make the pie chart more visually appealing or to adhere to specific color schemes:

Python
colors = ["gold", "yellowgreen", "lightcoral", "lightskyblue"]

plt.pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=140)
plt.show()

In this example, each slice of the pie chart is assigned a different color specified by the colors list. This can be useful for making the chart more distinguishable and aesthetically pleasing.

Adding a Legend

If your pie chart contains multiple slices, adding a legend can help in identifying each category:

Python
plt.pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=140)
plt.legend(labels, loc="best")
plt.show()

The plt.legend() function adds a legend to your pie chart, which is placed in the best location automatically.

Donut Charts

A donut chart is similar to a pie chart but with a hole in the center. You can create a donut chart by adjusting the wedgeprops:

Python
plt.pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=140, wedgeprops={"width": 0.3})
plt.show()

In this example, setting width to 0.3 creates a donut chart with a hole in the center.

Pie charts are ideal for showing the relative proportions of different categories within a dataset, and Matplotlib provides extensive customization options to make your pie charts both informative and visually appealing.