python logo

pie chart python

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

Matplotlib supports pie charts using the pie() function. You might like the Matplotlib gallery.

The matplotlib module can be used to create all kinds of plots and charts with Python. A pie chart is one of the charts it can create, but it is one of the many.

Related course: Data Visualization with Matplotlib and Python

Matplotlib pie chart

First import plt from the matplotlib module with the line import matplotlib.pyplot as plt
Then you can use the method plt.pie() to create a plot.

The code below creates a pie chart:

import matplotlib.pyplot as plt

# Data to plot
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice

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


The above code has the following output:

pie chart python pie chart python

You can define it’s sizes, which parts should explode (distance from center), which labels it should have and which colors it should have.

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

Matplotlib pie chart legend

To add a legend use the plt.legend() function. This adds a legend on top of the plot.

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")

It outputs this plot:

python pie chart python pie chart

While making the plot, don’t forget to call the method .show().

Download All Matplotlib Examples



Leave a Reply: