How to Create a Pie Chart in Matplotlib

Spread the love

In this post, you will learn How to create a Pie Chart in Matplotlib

plt.pie() –

Reading a Dataset to work with.

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/QueenCity.csv"
df = pd.read_csv(url)
df['Expenditure'] = df['Expenditure'].str.replace('$', '').str.replace(',', '')
df['Expenditure'] = df['Expenditure'].astype(float)
df.head()

Next, we need to find out the total expenditure by category.

exp = df.groupby('Category')['Expenditure'].sum().reset_index()
exp

Now to create a Pie Chart, we have to use plt.pie() method.

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.pie(exp['Expenditure'], labels=exp['Category'])
plt.title("Expenditure By Category")
plt.show()

Although we draw the pie chart but the percentage labels are missing and also the text is overlapping on each others. Let’ fix these.

To show the percentages, we need to use the autopct parameter.

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 8))
plt.pie(exp['Expenditure'], labels=exp['Category'], autopct='%0.2f%%')
plt.title("Expenditure By Category")
plt.show()

And to remove text overlapping, we can use the explode parameter. The length of the explode will equal to the number of categories we have.

import matplotlib.pyplot as plt

explode = [0, 0, 0, 0, 0, 0.2, 0.5, 0.3, 0]
plt.figure(figsize=(10, 8))
plt.pie(exp['Expenditure'], labels=exp['Category'], autopct='%0.2f%%',explode=explode)
plt.title("Expenditure By Category")
plt.show()

Rating: 1 out of 5.

Leave a Reply