By Hemanta Sundaray on 2022-03-18
We use a pie chart when we want to display elements of a data set as proportions of a whole.
In Matplotlib, we can make a pie chart with the command plt.pie, passing in the values we want to chart:
import matplotlib.pyplot as plt
brand_contribution = [40, 30, 20, 10]
brands=['Ritu Kumar', 'Label', 'Aarke', 'RI']
plt.pie(brand_contribution)
Output:
We also want to be able to understand what each slice of the pie represents. To do this, we can put labels on the chart itself:
import matplotlib.pyplot as plt
brand_contribution = [40, 30, 20, 10]
brands=['Ritu Kumar', 'Label', 'Aarke', 'RI']
plt.pie(brand_contribution, labels=brands)
This puts the category names into labels next to each corresponding slice:
One other useful labelling tool for pie charts is adding the percentage of the total that each slice occupies. Matplotlib can add this automatically with the keyword autopct. We pass in string formatting instructions to format the labels how we want. Some common formats are:
import matplotlib.pyplot as plt
brand_contribution = [40, 30, 20, 10]
brands=['Ritu Kumar', 'Label', 'Aarke', 'RI']
plt.pie(brand_contribution, labels=brands, autopct='%0.1f%%')
and the resulting chart would look like: