The Wayback Machine - https://web.archive.org/web/20240903042249/https://www.geeksforgeeks.org/matplotlib-tutorial/
Open In App

Matplotlib Tutorial

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

Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc. 

In this article, you’ll gain a comprehensive understanding of the diverse range of plots and charts supported by Matplotlib, empowering you to create compelling and informative visualizations for your data analysis tasks.

Matplotlib Getting Started

Before we start we will check if Python is Installed in your system, If not follow this article:

Creating Different Types of Plot

In data visualization, creating various types of plots is essential for effectively conveying insights from data. Below, we’ll explore how to create different types of plots using Matplotlib, a powerful plotting library in Python.

Line Graph in Matplotlib

Line graphs are commonly used to visualize trends over time or relationships between variables. We’ll learn how to create visually appealing line graphs to represent such data.

Example

Python3
import matplotlib.pyplot as plt 
# data to display on plots 
x = [3, 1, 3] 
y = [3, 2, 1] 

# This will plot a simple line chart
# with elements of x as x axis and y
# as y axis
plt.plot(x, y)
plt.title("Line Chart")

# Adding the legends
plt.legend(["Line"])
plt.show()

Output

Image

Stem Plot in Matplotlib

A stem plot, also known as a stem-and-leaf plot, is a type of plot used to display data along a number line. Stem plots are particularly useful for visualizing discrete data sets, where the values are represented as “stems” extending from a baseline, with data points indicated as “leaves” along the stems. let’s understand the components of a typical stem plot:

  • Stems: The stems represent the main values of the data and are typically drawn vertically along the y-axis.
  • Leaves: The leaves correspond to the individual data points and are plotted horizontally along the stems.
  • Baseline: The baseline serves as the reference line along which the stems are drawn.

Example

Python3
# importing libraries 
import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(0.1, 2 * np.pi, 41) 
y = np.exp(np.sin(x)) 

plt.stem(x, y, use_line_collection = True) 
plt.show() 

Output

Image

Bar chart in Matplotlib

A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. It can be created using the bar() method.

Example

Python3
import matplotlib.pyplot as plt 
# data to display on plots 
x = [3, 1, 3, 12, 2, 4, 4] 
y = [3, 2, 1, 4, 5, 6, 7] 

# This will plot a simple bar chart
plt.bar(x, y)

# Title to the plot
plt.title("Bar Chart")

# Adding the legends
plt.legend(["bar"])
plt.show()

Output

Image

Plotting Histogram in Matplotlib

A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. To create a histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables.

Example

Python3
import matplotlib.pyplot as plt 
# data to display on plots 
x = [1, 2, 3, 4, 5, 6, 7, 4] 
# This will plot a simple histogram
plt.hist(x, bins = [1, 2, 3, 4, 5, 6, 7])
# Title to the plot
plt.title("Histogram")
# Adding the legends
plt.legend(["bar"])
plt.show()

Output

Image

Scatter Plot in Matplotlib

Scatter plots are ideal for visualizing the relationship between two continuous variables. We’ll see how scatter plots help identify patterns, correlations, or clusters within data points.

Python3
import matplotlib.pyplot as plt 
# data to display on plots 
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]

# This will plot a simple scatter chart
plt.scatter(x, y)

# Adding legend to the plot
plt.legend("A")

# Title to the plot
plt.title("Scatter chart")
plt.show()

Output

Image

Stack Plot in Matplotlib

Stackplot, also known as a stacked area plot, is a type of plot that displays the contribution of different categories or components to the total value over a continuous range, typically time. It is particularly useful for illustrating changes in the distribution of data across multiple categories or groups.

Python3
import matplotlib.pyplot as plt

# List of Days
days = [1, 2, 3, 4, 5]

# No of Study Hours
Studying = [7, 8, 6, 11, 7]

# No of Playing Hours
playing = [8, 5, 7, 8, 13]

# Stackplot with X, Y, colors value
plt.stackplot(days, Studying, playing,
            colors =['r', 'c'])

# Days
plt.xlabel('Days')

# No of hours
plt.ylabel('No of Hours')

# Title of Graph
plt.title('Representation of Study and \
Playing wrt to Days')

# Displaying Graph
plt.show()

Output

Image

Box Plot in Matplotlib

A box plot, also known as a box-and-whisker plot, provides a visual summary of the distribution of a dataset. It represents key statistical measures such as the median, quartiles, and potential outliers in a concise and intuitive manner. Box plots are particularly useful for comparing distributions across different groups or identifying anomalies in the data.

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


# Creating dataset
np.random.seed(10)
data = np.random.normal(100, 20, 200)

fig = plt.figure(figsize =(10, 7))

# Creating plot
plt.boxplot(data)

# show plot
plt.show()

Output

Image

Pie Chart in Matplotlib

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. The area of slices of the pie represents the percentage of the parts of the data. The slices of pie are called wedges. The area of the wedge is determined by the length of the arc of the wedge.

Python3
import matplotlib.pyplot as plt 
# data to display on plots 
x = [1, 2, 3, 4] 

# this will explode the 1st wedge
# i.e. will separate the 1st wedge
# from the chart
e  =(0.1, 0, 0, 0)

# This will plot a simple pie chart
plt.pie(x, explode = e)

# Title to the plot
plt.title("Pie chart")
plt.show()

Output

Image

Error Plot in Matplotlib

Error plots display the variability or uncertainty associated with each data point in a dataset. They are commonly used in scientific research, engineering, and statistical analysis to visualize measurement errors, confidence intervals, standard deviations, or other statistical properties of the data. By incorporating error bars into plots, we can convey not only the central tendency of the data but also the range of possible values around each point.

Python3
# importing matplotlib
import matplotlib.pyplot as plt 


# making a simple plot
x =[1, 2, 3, 4, 5, 6, 7]
y =[1, 2, 1, 2, 1, 2, 1]

# creating error
y_error = 0.2

# plotting graph
plt.plot(x, y)

plt.errorbar(x, y,
            yerr = y_error,
            fmt ='o')

Output

Image

Violin Plot in Matplotlib

A violin plot is a method of visualizing the distribution of numerical data and its probability density. It is similar to a box plot but provides additional insights into the data’s distribution by incorporating a kernel density estimation (KDE) plot mirrored on each side. This allows for a more comprehensive understanding of the data’s central tendency, spread, and shape.

Python3
import numpy as np 
import matplotlib.pyplot as plt 

# creating a list of 
# uniformly distributed values 
uniform = np.arange(-100, 100) 

# creating a list of normally 
# distributed values 
normal = np.random.normal(size = 100)*30

# creating figure and axes to 
# plot the image 
fig, (ax1, ax2) = plt.subplots(nrows = 1, 
                            ncols = 2, 
                            figsize =(9, 4), 
                            sharey = True) 

# plotting violin plot for 
# uniform distribution 
ax1.set_title('Uniform Distribution') 
ax1.set_ylabel('Observed values') 
ax1.violinplot(uniform) 

# plotting violin plot for 
# normal distribution 
ax2.set_title('Normal Distribution') 
ax2.violinplot(normal) 

# Function to show the plot 
plt.show() 

Output

Image

3D Plots in Matplotlib

Sometimes, data visualization requires a three-dimensional perspective. We’ll delve into creating 3D plots to visualize complex relationships and structures within multidimensional datasets.

Python3
import matplotlib.pyplot as plt 
# Creating the figure object
fig = plt.figure()

# keeping the projection = 3d
# creates the 3d plot
ax = plt.axes(projection = '3d')

Output:

Image

The above code lets the creation of a 3D plot in Matplotlib. We can create different types of 3D plots like scatter plots, contour plots, surface plots, etc. Let’s create a simple 3D line plot.

Python3
import matplotlib.pyplot as plt 
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
z = [1, 8, 27, 64, 125]
# Creating the figure object
fig = plt.figure()
# keeping the projection = 3d
# creates the 3d plot
ax = plt.axes(projection = '3d')
ax.plot3D(z, y, x)

Output

Image




Similar Reads

Matplotlib.colors.rgb_to_hsv() in Python
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. matplotlib.colors.rgb_to_hsv() The matplotlib.colors.rgb_to_hsv() function belongs to the matplotlib.colors module. The matplotlib.colors.
2 min read
Violinplot in Python using axes class of Matplotlib
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. #Sample Code # Implementation of matplotlib functi
2 min read
Matplotlib.pyplot.broken_barh() in Python
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. matplotlib.pyplot.broken_barh() The function broken_barh() is used to Plot a horizontal sequence of rectan
2 min read
Matplotlib.ticker.MultipleLocator Class in Python
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. matplotlib.ticker.MultipleLocator The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a b
1 min read
Matplotlib.axes.Axes.contourf() 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.contourf() Function The Axes.
2 min read
Matplotlib.axes.Axes.fill() 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.fill() Function The Axes.fill
2 min read
matplotlib.axes.Axes.fill_betweenx() 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.fill_betweenx() Function The
3 min read
Matplotlib.gridspec.GridSpec Class in Python
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. matplotlib.gridspec.GridSpec The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For th
3 min read
Matplotlib.pyplot.axis() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. matplotlib.pyplot.axis() This function is us
1 min read
How to resize Matplotlib RadioButtons?
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. Radio buttons are the most commonly used widgets in visualization. Radio buttons let us choose between multiple options in a visualization
3 min read
Matplotlib.axis.Axis.get_minorticklines() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.get_minorticklines() Function The Axis.get_minorticklines() function in axis module of matplotlib library is
2 min read
3D Wireframe plotting in Python using Matplotlib
To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: C/C++ Code # importing modules from
1 min read
Matplotlib.patches.CirclePolygon class in Python
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. matplotlib.patches.CirclePolygon The matplotlib.patches.CirclePolygon class is used for polygon-approximation of a circle patch. It is use
3 min read
Matplotlib.pyplot.get_fignums() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.get_fignums() method The ge
2 min read
How to change the size of axis labels in Matplotlib?
Matplotlib is a great data plotting tool. It's used for visualizing data and also for presenting the data to your team on a presentation or for yourself for future reference. So, while presenting it might happen that the "X-label" and "y-label" are not that visible and for that reason, we might want to change its font size. So in this article, we a
2 min read
Python | Matplotlib.pyplot ticks
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 introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge
3 min read
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
Matplotlib.pyplot.waitforbuttonpress() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.waitforbuttonpress() method
2 min read
Multiplots in Python using Matplotlib
Matplotlib is a Python library that can be used for plotting graphs and figures. Plotting multiplots or multiple plots are often required either for comparing the two curves or show some gradual changes in the multiple plots, and this can be done using Subplots. Subplots are one of the most important and fundamental concepts to be understood while
3 min read
Matplotlib.axes.Axes.streamplot() 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.streamplot() Function The Axe
3 min read
Matplotlib.axis.Axis.set_figure() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.set_figure() Function The Axis.set_figure() function in axis module of matplotlib library is used to set the
2 min read
Matplotlib.pyplot.streamplot() in Python
Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is: ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing) Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each p
7 min read
Plot Single 3D Point on Top of plot_surface in Python - Matplotlib
Matplotlib is a widely-used plotting library in Python that offers various tools and functionalities for creating 2D and 3D visualizations. In this article, we will explore how to use Matplotlib to plot a single 3D point on top of a 3d surface plot. Plot Single 3D Point on Top of SurfaceLet us understand the Plotting single 3D point on top of the p
5 min read
Different plotting using pandas and matplotlib
We have different types of plots in matplotlib library which can help us to make a suitable graph as you needed. As per the given data, we can make a lot of graph and with the help of pandas, we can create a dataframe before doing plotting of data. Let's discuss the different types of plot in matplotlib by using Pandas. Use these commands to instal
4 min read
Matplotlib.axes.Axes.set_zorder() 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.set_zorder() Function The Axe
1 min read
Python | Working with PNG Images using 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 introduced by John Hunter in the year 2002. One of the greatest benefits of visualization is that it allows us visual access to hug
3 min read
How to add a legend to a scatter plot in Matplotlib ?
In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph. Syntax: matplotlib.pyplot.legend( ["title_1", "Title_2"], ncol = 1 , loc = "upper left" ,bbox_to_ancho
2 min read
Remove the legend border in Matplotlib
In this article, we will learn how to Remove the legend border in Matplotlib. Let's discuss some concepts : A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes. Approach: Import Library (Matplotlib)Import / create data.Plot a chart.Add le
2 min read
Python | Matplotlib Graph plotting using object oriented API
In object-oriented API, first, we create a canvas on which we have to plot the graph and then we plot the graph. Many people prefer object-oriented API because it is easy to use as compared to functional API. Let's try to understand this with some examples. Example #1: # importing matplotlib library import matplotlib.pyplot as plt # x axis values x
2 min read
How to Place Legend Outside of the Plot in Matplotlib?
In this article, we will see how to put the legend outside the plot. 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 introduced by John H
3 min read
Article Tags :
Practice Tags :