Create A Pie Chart Using Matplotlib In Python

Hello Pythonisatas, welcome back. Let’s create a pie chart using Matplotlib in Python.

How to Create a Pie Chart using Matplotlib

To create a pie chart like the one below:

create a pie chart using matplotlib
  1. Install and Import Matplotlib’s pyplot module
  2. Then create a list of data, a list of labels, and a list of colors
  3. Now plot the values using the pie method.
  4. Provide this chart: a title and then using the show() method plot the chart.
import matplotlib.pyplot as plt

my_data = [30, 30, 30]
my_labels = ["label1", "label2", "label3"]
c = ['pink', '#b3ecff', '#90EE90']

plt.pie(my_data, labels=my_labels, colors=c)

plt.title("My Pie Chart")

plt.show()

What Is Explode In Pie Chart Python?

Maybe you want one or more parts of this pie chart to show up highlighted like this:

What Is Explode In Pie Chart Python?

To create an exploded chart like this:

  1. Create a list of explode values.
  2. Add this list to the pie() method
import matplotlib.pyplot as plt

my_data = [30, 30, 30]
my_labels = ["label1", "label2", "label3"]
c = ['pink', '#b3ecff', '#90EE90']
myexplode = [0, 0, 0.2]

plt.pie(my_data, labels=my_labels, colors=c, explode=myexplode)

plt.title("My Pie Chart")

plt.show()

How do I add percentages to a pie chart in Matplotlib?

You might want to show the percentage occupied by each part like this:

How do I add percentages to a pie chart in Matplotlib?

Here’s how you add the percentage here:

  1. Add autopct attribute then, provide the format in which you want to display.
  2. %1.1f means floating point value with 1 decimal point.
import matplotlib.pyplot as plt

my_data = [30, 30, 30]
my_labels = ["label1", "label2", "label3"]
c = ['pink', '#b3ecff', '#90EE90']

plt.pie(my_data, labels=my_labels, colors=c, autopct="%1.1f")

plt.title("My Pie Chart")

plt.show()

Leave a Reply