python logo

pie chart python

Python hosting: Host, run, and code Python in the cloud!

Matplotlib is a versatile library in Python that supports the creation of a wide variety of charts, including pie charts. Check out the Matplotlib gallery to explore more chart types.

Related course: Data Visualization with Matplotlib and Python

Crafting a Pie Chart with Matplotlib

To begin with, ensure you’ve imported the required module using: import matplotlib.pyplot as plt. Once done, the plt.pie() method is readily available for creating your pie chart.

Here’s a simple example that demonstrates how to generate a pie chart:

import matplotlib.pyplot as plt

# Defining data for the chart
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice

# Plotting the chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

With the above code, the result is a visually pleasing pie chart.

pie chart python

Matplotlib allows for extensive customization. You can determine slice sizes, which segments should stand out from the center (explode), their respective labels, and even their colors.

plt.pie(sizes, explode=explode, labels=labels, colors=colors, ...)

Enhancing Your Pie Chart with a Legend

To make your pie chart even more informative, consider adding a legend using the plt.legend() function. This overlays a legend on your chart, providing clarity.

import matplotlib.pyplot as plt

labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
sizes = [38.4, 40.6, 20.7, 10.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches, labels, loc="best")

This code renders a pie chart that’s enriched with a legend.

python pie chart

Always remember, after setting up your plot, call the method .show() to ensure it gets displayed.

For more examples and downloadable code, click here.

Navigation: [Back] [Next]

Leave a Reply: