A pie chart is a graphic representation of quantitative information by means of a circle divided into sectors, in which the relative sizes of the areas (or central angles) of the sectors correspond to the relative sizes or proportions of the quantities.
To create a pie chart in Matplotlib
we use the pie()
method.
The pie()
method takes the parameter value data array
which represents the wedge sizes of the pie chart.
from matplotlib.pyplot import pie, showfrom numpy import arraydata_set = array([50, 20, 25, 15])pie(data_set)show()
Line 1: We import the pie()
and show()
functions from matplotlib.pyplot
module.
Line 2: We import the array()
function from NumPy
library.
Line 4: We use the array()
method to create a data array.
Line 6: We use the pie()
method to plot a pie chart.
Line 7: We use the show()
method to show our plot.
To add a label to a pie chart, the pie()
function must take another parameter value called labels
.
pie(x, labels)
from matplotlib.pyplot import pie, showfrom numpy import arraydata_set = array([50, 20, 25, 15])my_labels = ["Tomatoes", "Apples", "Mangoes", "Tiger nuts"]pie(data_set, labels = my_labels)show()
Line 1: We import the pie()
and show()
functions from matplotlib.pyplot
module.
Line 2: We import the array()
function from NumPy
library.
Line 4: We use the array()
method to create a data array data_set
.
Line 5: We create a list variable my_labels
which will serve as the value for the label
parameter.
Line 7: We use the pie()
method to plot the data array data_set
and pass the variable my_labels
as the labels
parameter value.
Line 8: We use the show()
method to show our plot.