Python Pie Chart

A pie chart shows a circle that is divided into sectors and each sector represents a proportion of the whole. For example, we can take different departments in a company and their employees. Suppose, there are 4 departments and their employees are in the percentages of 50--, 20--, 15-- and 15--. These can be represented as slices in a pie chart. To create a pie chart, we can use pie() function as:

plt.pie(slices, labels=depts, colors=cols, startangle=90, explode=(0, 0.2, 0, 0), shadow=True, autopct='--.1f----')

Here, labels=depts indicates a list of labels. colors=cols indicates a list of colors. startangle=90 indicates that the pie chart will start at 90 degrees (12 o'clock position). If this option is not mentioned, then it starts by default at 0 degrees (3 o'clock position). The option explode=(0,0.2, 0,0) indicates whether the slices in the pie chart should stand out or not. Here, 0 indicates that the corresponding slide will not come out of the chart. But the next 0.2 indicates that the second slice should come out slightly. Its values 0.1 to 1 indicate how much it should come out of the chart. The option shadow=True indicates that the pie chart should be displayed with a shadow. This will improve the look of the chart. The option autopct='--.1f----' indicates how to display the percentages on the slices. Here, --.1 indicates that the percentage value should be displayed with 1 digit after decimal point. The next two-- symbols indicate that only one symbol is to be displayed.

Python Pie Chart Example

A program to display a pie chart showing the percentage of employees in each department of a company.

CopiedCopy Code

#to display employees of different depts in pie chart 
import matplotlib.pyplot as plt 
#take the percentages of employees of 4 departments 
slices = [50, 20, 15, 15] 
#take the departments names 
depts = ['Sales', 'Production', 'HR', 'Finance'] 
#take the colors for each department 
cols = ['magenta', 'cyan', 'brown', 'gold'] 
#create a pie chart 
plt.pie(slices, labels=depts, colors=cols, startangle=90, explode=(0, 0, 0.2, 0), shadow=True, autopct='--.1f----')
#set titles and legend 
#show the pie chart