The Wayback Machine - https://web.archive.org/web/20240817125209/https://www.geeksforgeeks.org/plot-a-pie-chart-in-python-using-matplotlib/
Open In App

Plot a pie chart in Python using Matplotlib

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. Pie charts are commonly used in business presentations like sales, operations, survey results, resources, etc. as they provide a quick summary. In this article, let’s understand how to create pie chart in python with pie diagram.

How to draw pie chart?

Matplotlib API has pie() function in its pyplot module which create a pie chart representing the data in an array. let’s create pie chart in python.

Syntax: matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, autopct=None, shadow=False)
Parameters: 
data represents the array of data values to be plotted, the fractional area of each slice is represented by data/sum(data). If sum(data)<1, then the data values returns the fractional area directly, thus resulting pie will have empty wedge of size 1-sum(data). 
labels is a list of sequence of strings which sets the label of each wedge. 
color attribute is used to provide color to the wedges. 
autopct is a string used to label the wedge with their numerical value. 
shadow is used to create shadow of wedge. 
 

Let’s create a simple pie chart using the pie() function:

Python
# Import libraries
from matplotlib import pyplot as plt
import numpy as np


# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)

# show plot
plt.show()

Output: 

pie-chart-python


A pie chart can be customized on the basis several aspects. The startangle attribute rotates the plot by the specified degrees in counter clockwise direction performed on x-axis of pie chart. shadow attribute accepts boolean value, if its true then shadow will appear below the rim of pie. Wedges of the pie can be customized using wedgeprop which takes Python dictionary as parameter with name values pairs denoting the wedge properties like linewidth, edgecolor, etc. By setting frame=True axes frame is drawn around the pie chart.autopct controls how the percentages are displayed on the wedges. Let us try to modify the above pie chart in python.

The explode parameter separates a portion of the chart, and colors define each wedge’s color. The autopct function customizes text display, and legend and title functions enhance chart readability and aesthetics. 

Python
# Import libraries
import numpy as np
import matplotlib.pyplot as plt


# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]


# Creating explode data
explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)

# Creating color parameters
colors = ("orange", "cyan", "brown",
          "grey", "indigo", "beige")

# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}

# Creating autocpt arguments


def func(pct, allvalues):
    absolute = int(pct / 100.*np.sum(allvalues))
    return "{:.1f}%\n({:d} g)".format(pct, absolute)


# Creating plot
fig, ax = plt.subplots(figsize=(10, 7))
wedges, texts, autotexts = ax.pie(data,
                                  autopct=lambda pct: func(pct, data),
                                  explode=explode,
                                  labels=cars,
                                  shadow=True,
                                  colors=colors,
                                  startangle=90,
                                  wedgeprops=wp,
                                  textprops=dict(color="magenta"))

# Adding legend
ax.legend(wedges, cars,
          title="Cars",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Customizing pie chart")

# show plot
plt.show()

Output: 
 

pie-chart-python


Nested Pie Chart

Python
# Import libraries
from matplotlib import pyplot as plt
import numpy as np


# Creating dataset
size = 6
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']

data = np.array([[23, 16], [17, 23],
                 [35, 11], [29, 33],
                 [12, 27], [41, 42]])

# normalizing data to 2 pi
norm = data / np.sum(data)*2 * np.pi

# obtaining ordinates of bar edges
left = np.cumsum(np.append(0,
                           norm.flatten()[:-1])).reshape(data.shape)

# Creating color scale
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(6)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9,
                              10, 12, 13, 15,
                              17, 18, 20]))

# Creating plot
fig, ax = plt.subplots(figsize=(10, 7),
                       subplot_kw=dict(polar=True))

ax.bar(x=left[:, 0],
       width=norm.sum(axis=1),
       bottom=1-size,
       height=size,
       color=outer_colors,
       edgecolor='w',
       linewidth=1,
       align="edge")

ax.bar(x=left.flatten(),
       width=norm.flatten(),
       bottom=1-2 * size,
       height=size,
       color=inner_colors,
       edgecolor='w',
       linewidth=1,
       align="edge")

ax.set(title="Nested pie chart")
ax.set_axis_off()

# show plot
plt.show()

Output: 
 

pie-chart-python

Conclusion

In summary, creating a pie chart in Python using Matplotlib’s pie() function is a straightforward process. Customizations such as explode, colors, autopct, and others offer flexibility in visual representation, making pie charts effective for summarizing data in business presentations.

Frequently Asked Questions (FAQs)

Q. How do you create a pie chart using matplotlib?

Use Matplotlib’s pie() function, providing data, labels, colors, and other optional parameters for customization.

Q.How do I show percentages in a pie chart using matplotlib?

Utilize the autopct parameter in the pie() function to display percentages on the wedges.

Q.How do you plot a pie chart?

Use Matplotlib’s pie() function, passing data, labels, and other optional parameters to create a pie chart in Python.

Q.How do you show values in a pie chart in Python?

The autopct parameter in Matplotlib’s pie() function allows you to display numerical values on the pie chart.

Q.Why use pie chart in Python?

Pie charts offer a visual representation of data percentages, making them effective for summarizing and presenting information in a clear and concise manner.
 



Previous Article
Next Article

Similar Reads

How to set border for wedges in Matplotlib pie chart?
Pie charts can be used for relative comparison of data. Python offers several data visualization libraries to work with. The Matplotlib library offers different types of graphs and inbuild methods and properties to manipulate the graph. The wedges in the pie chart can be given a border using the wedgeprops attribute of the pie() method of matplotli
3 min read
Radially displace pie chart wedge in Matplotlib
Pie charts are statistical graphs divided into slices that represent different data values and sum up to 100%. Python is one of the most popularly used programming languages for data visualization. Python has multiple data visualization libraries and Matplotlib is one of them. Matplotlib is widely used because of its simplicity and ease of implemen
3 min read
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
Prerequisites: PandasMatplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are
2 min read
matplotlib.axes.Axes.pie() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.pie() Function The Axes.pie()
3 min read
Plot Candlestick Chart using mplfinance module in Python
Candlestick chart are also known as a Japanese chart. These are widely used for technical analysis in trading as they visualize the price size within a period. They have four points Open, High, Low, Close (OHLC). Candlestick charts can be created in python using a matplotlib module called mplfinance. Installation:pip install mplfinancemplfinance.ca
2 min read
Donut Chart using Matplotlib in Python
Prerequisites: Pie Chart in matplotlib Donut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Donut charts are
4 min read
Plot 2D data on 3D plot in Python
In this article, we will be learning about how to plot 2D data on 3D plot in Python. We will be demonstrating two methods in order to learn the concept. The first method will be using Matplotlib.pyplot.gca() function which is a pyplot module of the matplotlib library. But before that, we need to configure where are we going to create our project an
4 min read
Make a violin plot in Python using Matplotlib
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more information, refer to Python Matplotlib – An Overview Wh
3 min read
Plot the magnitude spectrum in Python using Matplotlib
A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described. A periodic signal can be represented using the below sine function: y = A sin(w*t + Q) In which A represents the amplitude(in
3 min read
Plot the phase spectrum in Python using Matplotlib
A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described. A periodic signal can be represented using the below sine function: y = A sin(w*t + Q) In which A represents the amplitude(in
3 min read
Plot Mathematical Expressions in Python using Matplotlib
For plotting equations we will use two modules Matplotlib.pyplot and Numpy. This module helps you to organize your Python code logically. Numpy Numpy is a core library used in Python for scientific computing. This Python library supports you for a large, multidimensional array object, various derived objects like matrices and masked arrays, and ass
5 min read
Plot the power spectral density using Matplotlib - Python
matplotlib.pyplot.psd() function is used to plot power spectral density. In the Welch's average periodogram method for evaluating power spectral density (say, Pxx), the vector 'x' is divided equally into NFFT segments. Every segment is windowed by the function window and detrended by the function detrend. The overlap between segments is given by 'n
6 min read
Contour Plot using Matplotlib - Python
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables we want to plot then the response Z will be plotted as slices on the X-Y plane due to which contours are sometimes referred as Z-slices or iso-response. Contour plots are widely used to vis
2 min read
Tri-Surface Plot in Python using Matplotlib
A Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex. This type of plot is created where the evenly sa
2 min read
Plot a quadrilateral mesh in Python using Matplotlib
Matplotlib a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack. Matplotlib has the ability to play well with many operating systems and graphics backends as well. matplotlib.pyplot can also be used for MATLAB-like plotting framework. Plotting a quadrilateral mesh pcolormesh() function
3 min read
Create a pseudocolor plot of an unstructured triangular grid in Python using Matplotlib
Matplotlib is a Python module which can be used for data visualization; and analyse the data graphically in the form of pie-chart, histogram, bar graph and many more. It also has an ability to generate MATLAB-like frameworks. Unstructured triangular grid An unstructured triangular grid contains n_points points and n_tri triangles which can either b
5 min read
How to plot a complex number in Python using Matplotlib ?
In this article we will learn how to plot complex number in Python using Matplotlib. Let's discuss some concepts : Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was int
3 min read
Box Plot in Python using Matplotlib
A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis
5 min read
How to calculate and plot the derivative of a function using matplotlib and python?
In this article, we are going to learn how to calculate and plot the derivative of a function using Matplotlib in Python. In our higher standard in school, we all have studied derivatives in the mathematics syllabus of calculus and we know that calculus is a fundamental branch that deals with the study of rates of change and slopes of curves. The d
4 min read
Plot 2-D Histogram in Python using Matplotlib
In this article, we are going to learn how to plot 2D histograms using Matplotlib in Python. The graphical representation of the distribution of a dataset is known as a histogram. They can be used to show the frequency of values using in a dataset using bins which are obtained by dividing the data into a set of intervals. A histogram that shows the
4 min read
Understanding Gain Chart and Lift Chart
The gain chart and lift chart are two measures that are used for Measuring the benefits of using the model and are used in business contexts such as target marketing. It's not just restricted to marketing analysis. It can also be used in other domains such as risk modeling, supply chain analytics, etc. In other words, Gain and Lift charts are two a
3 min read
How to display the value of each bar in a bar chart using Matplotlib?
In this article, we are going to see how to display the value of each bar in a bar chart using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib - Using matplotlib.axes.Axes.text() function.Use matplotlib.pyplot.text() function. Example 1: Using matplotlib.axes.Axes.text() function: This functio
2 min read
Line chart in Matplotlib - Python
Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of Matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. In this article, we will learn about line charts and matplotlib simple line plots in Pytho
6 min read
Autocorrelation plot using Matplotlib
Autocorrelation plots are a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelations for data values at varying time lags. Characteristics Of Autocorrelation Plot : It measures a set of current values against a set of past values and finds whether they correlate.It is the correlation of
3 min read
How to plot data from a text file using Matplotlib?
Perquisites: Matplotlib, NumPy In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like: Bar GraphLine GraphScatter GraphHistogram Graph and many. In this article, we will learn how we can load data from a file to
3 min read
How to plot two dotted lines and set marker using Matplotlib?
In this article, we will plot two dotted lines and set markers using various functions of the matplotlib package in the python programming language. We can use the pyplot.plot along with the linestyle parameter function to draw the dotted line. matplotlib.pyplot.plot(array1,array2,linestyle='dotted') Note: To set the marker, we have to use the labe
2 min read
How to Save a Plot to a File Using Matplotlib?
Matplotlib is a widely used Python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. In this article, we will see how to save a Matplotlib plot as an image file. Save a plot in MatplotlibBelow are the ways by which we can save a plot to a file using Matplotlib in Python: Us
3 min read
Scatter Plot on Polar Axis using Matplotlib
Scatter plots are essential for comprehending the interactions between variables in data visualization. Although scatter plots are frequently created in Cartesian coordinates, we can also make scatter plots on polar axes using Matplotlib. With this feature, one can see circular or angular data in innovative ways, such as cyclical trends or directed
4 min read
Save Plot To Numpy Array using Matplotlib
Saving a plot to a NumPy array in Python is a technique that bridges data visualization with array manipulation allowing for the direct storage of graphical plots as array representations, facilitating further computational analyses or modifications within a Python environment. Let's learn how to Save Plot to NumPy Array using Matplotlib. How to Sa
4 min read
Normal Distribution Plot using Numpy and Matplotlib
In this article, we will see how we can create a normal distribution plot in python with numpy and matplotlib module.  What is Normal Distribution?Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics becaus
3 min read
Practice Tags :
three90RightbarBannerImg