38 Piecharts
38 Piecharts
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
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
Colors
Legend
To add a list of explanation for each wedge, use the legend() function:
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
# 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']
# Wedge properties
wp = { 'linewidth' : 1, 'edgecolor' : "green" }
# 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))