How to create a pie chart in Matlab and Python

What is a pie chart?

The pie chart is a circular plot that gives the statistical visualization of the data series. The percentage of data is the area of a pie chart, and each type of data has a slice in the pie chart; these are called wedges. We can find the area of wedges using the formula of an arc.

In this formula, x is the size of the wedge. We get the arc length using the formula, and we can multiply it by the total length of the dataset to get the number of data of that wedge.

Explanation

The illustration above shows a pie plot of a dataset for cars, where each wedge indicates the number of cars in a showroom. Each color represents a different wedge and data. Let's move forward with plotting the pie chart in Matlab and Python.

Plot a pie chart on Matlab

Plotting a pie chart in Matlab is a straightforward method. Matlab provides an elementary function to plot the pie chart, pie(x); x is the variable with the data stored in it.

Other than simply using pie(x), we can pass some other informative variables to the function.

  • Explode: We can offset wedges using 1 in explode array.

  • Labels: We can add labels to the wedges using the labels variable.

Program

The program below will create a pie chart using the specified data.

b= [20 30 40 30]
explode = [1 0 1 0]
hf = figure ();
pie(b,explode)
title ("Pie Plot with Explode");
labels={'a','b','c','d'}
hf1 = figure ();
pie(b,labels)
title ("Pie Plot with Labels");

Explanation

  • Lines 1–2: We set values to the variables.

  • Lines 3–5: We plot the pie chart with explode.

  • Lines 8–11: We set labels and plot the pie chart with labels.

Plot a pie chart in Python

We can plot a pie chart in Python using the matplotlib library. Python offers a variety of built-in libraries to perform data analysis, and visualizations are part of that analysis. First, we must import the matplotlib library and specify some variables to plot them.

Other than simply plotting a pie chart, we can plot other informative variables.

  • Explode: We can offset wedges using 1 in explode array.

  • Labels: We can add labels to the wedges using the labels variable.

Program

The program below will create a pie chart using the specified data.

import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [1, 0, 0, 0]
plt.pie(y, labels = mylabels, explode = myexplode)
plt.show()

Explanation

  • Lines 1–2: We import libraries to plot the graph.

  • Lines 4–6: We set values to the variables.

  • Lines 8–9: We plot the graph using plt.pie(), and output it using plt.show().

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved