How to make a pie chart in Python Matplotlib?

A pie chart shows the percentage of each category in the whole unit. In the pie chart, each arc corresponds to the proportion of a category to the total.

To draw a pie chart in Matplotlib, you must follow the following steps:

Step 1: You must collect the data that you want to show on a pie chart. It is important to understand that data must be in the form of a list, NumPy array, or pandas DataFrame.

For example, the following is the data of the world energy consumption of resources.

data = [24,6,6,36,28]
label = ['Natural Gas', 'Hydro', 'Nuclear', 'Oil', 'Coal']

Step 2: In this step, you make the pie chart. Matplotlib provides the plt.pie() method to draw the pie chart. You pass the data and the labels associated with each category to the plt.pie() method.

The syntax for the plt.pie() method is

plt.pie(data, labels=None, explode=None, autopct=None, colors=None, startangle=0, shadow=False)

You can use the following code as a template for making pie chart in Matplotlib.

import matplotlib.pyplot as plt

data = [24, 6, 6, 36, 28]
label = ['Natural Gas', 'Hydro', 'Nuclear', 'Oil', 'Coal']

plt.pie(data, labels=label, autopct='%1.1f%%')
plt.title('World Energy Consumption')
plt.axis('equal')
plt.show()

Output

Matplotlib pie chart

Step 3: This step is about customizing and styling the pie chart. Matplotlib provides different arguments using which you can style the pie chart.

Following is the explanation of the arguments that you can pass to the plt.pie() method:

  • colors: colors argument enables you to specify the color of each slice of the pie chart.
  • explode: If you want to offset a particular slice from the pie chart, then use the explode argument.
  • autopct: It is used to show the percentage of each category inside the slices. Here, you specify the format string. For example, '%1.1f%%'.
  • shadow: When you want to show the shadow of each slice, then pass True to the shadow argument.
  • startangle: It is used to specify the angle at which the first slice must start.

The below code shows you how to style the pie chart:

import matplotlib.pyplot as plt

data = [24, 6, 6, 36, 28]
label = ['Natural Gas', 'Hydro', 'Nuclear', 'Oil', 'Coal']

plt.pie(data, labels=label, autopct='%1.1f%%', explode=[0,0,0,0.1,0], shadow=True, startangle=90)
plt.title('World Energy Consumption')
plt.axis('equal')
plt.show()

Output

Python pie chart

Recommended Posts