0% found this document useful (0 votes)
15 views7 pages

38 Piecharts

This document explains how to create pie charts in Python using Matplotlib's pyplot module. It covers various features such as adding labels, changing start angles, exploding wedges, customizing colors, and adding legends. Several code examples illustrate how to implement these features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views7 pages

38 Piecharts

This document explains how to create pie charts in Python using Matplotlib's pyplot module. It covers various features such as adding labels, changing start angles, exploding wedges, customizing colors, and adding legends. Several code examples illustrate how to implement these features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

pie chart in Python using Matplotlib

A Pie Chart is a circular statistical plot that can display only one series of
data. The area of the chart is the total percentage of the given data. The
area of slices of the pie represents the percentage of the parts of the data.
The slices of pie are called wedges. The area of the wedge is determined
by the length of the arc of the wedge. The area of a wedge represents the
relative percentage of that part with respect to whole data. Pie charts are
commonly used in business presentations like sales, operations, survey
results, resources, etc as they provide a quick summary.

With Pyplot, you can use the pie() function to draw pie charts:

Example
Import matplotlib.pyplot as plt
import numpy as np

y = np.array([35,25,25,15])

plt.pie(y)
plt.show()

As you can see the pie chart draws one piece (called a wedge) for each
value in the array (in this case [35, 25, 25, 15]).
By default the plotting of the first wedge starts from the x-axis and
move counterclockwise:

Labels:
Add labels to the pie chart with the label parameter.
The label parameter must be an array with one label for each wedge:

Example
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)


plt.show()
Start Angle
As mentioned the default start angle is at the x-axis, but you can change the start
angle by specifying a startangle parameter.
The startangle parameter is defined with an angle in degrees, default angle is 0:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels, startangle = 90)


plt.show()

Explode
Maybe you want one of the wedges to stand out? The explode parameter allows you
to do that.
The explode parameter, if specified, and not None, must be an array with one value
for each wedge.
Each value represents how far from the center each wedge is displayed:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]

plt.pie(y, labels = mylabels, explode = myexplode)


plt.show()

Colors

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]

plt.pie(y, labels = mylabels, colors = mycolors)


plt.show()
You can use Hexadecimal color values, any of the 140 supported color names, or one
of these shortcuts:
'r' - Red
'g' - Green
'b' - Blue
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White

Legend
To add a list of explanation for each wedge, use the legend() function:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)


plt.legend()
plt.show()

Creating Pie Chart


Matplotlib API has pie() function in its pyplot module which create a pie
chart representing the data in an array.

Syntax:matplotlib.pyplot.pie(data, explode=None, labels=None,


colors=None, autopct=None, shadow=False)
Parameters:
data:represents the array of data values to be plotted, the
fractional area of each slice is represented by data/sum(data). If
sum(data)<1, then the data values returns the fractional area
directly, thus resulting pie will have empty wedge of size 1-
sum(data).
Labels is a list of sequence of strings which sets the label of each
wedge.
Color attribute is used to provide color to the wedges.
Autopct is a string used to label the wedge with their numerical
value.
Shadow is used to create shadow of wedge.

# Import libraries
from matplotlib import pyplot as plt
import numpy as np

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)

# show plot
plt.show()
# Import libraries
import numpy as np
import matplotlib.pyplot as plt

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating explode data


explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)

# Creating color parameters


colors = ( "orange", "cyan", "brown",
"grey", "indigo", "beige")

# Wedge properties
wp = { 'linewidth' : 1, 'edgecolor' : "green" }

# Creating autocpt arguments


def func(pct, allvalues):
absolute = int(pct / 100.*np.sum(allvalues))
return "{:.1f}%\n({:d} g)".format(pct, absolute)

# Creating plot
fig, ax = plt.subplots(figsize =(10, 7))
wedges, texts, autotexts = ax.pie(data,
autopct = lambda pct: func(pct, data),
explode = explode,
labels = cars,
shadow = True,
colors = colors,
startangle = 90,
wedgeprops = wp,
textprops = dict(color ="magenta"))

# Adding legend
ax.legend(wedges, cars,
title ="Cars",
loc ="center left",
bbox_to_anchor =(1, 0, 0.5, 1))

plt.setp(autotexts, size = 8, weight ="bold")


ax.set_title("Customizing pie chart")
# show plot
plt.show()

You might also like