Visualizing data helps us understand and share information more effectively. In Python Matplotlib is one of the best tools for creating visualizations. It’s powerful, flexible, and lets you make many types of plots, from simple line charts to advanced animations. This tutorial will guide you step by step through using Matplotlib.
Setting Up Matplotlib
Before using Matplotlib, ensure you have it installed. You can install it using pip:
pip install matplotlib
Once installed, you can import it into your Python script:
import matplotlib.pyplot as plt
Essential Role of Pyplot in Matplotlib
Pyplot is a submodule of the Matplotlib library in Python providing a beginner-friendly tool for creating visualizations with minimal code. It helps transform dull data into engaging and interactive plots, making it easier to analyze and draw meaningful insights for informed decision-making.
Syntax:
matplotlib.pyplot.plot()
For more detailed information about Matplotlib Pyplot please refer to: Matplotlib Pyplot
Creating Different Types of Plots
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. Each type of plot in Matplotlib is designed to address specific analytical scenarios, making them valueable tools for businesses looking for getting insights for better decision making in the industry.
1. Line Graph
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
Python
import matplotlib.pyplot as plt
x = [3, 1, 3]
y = [3, 2, 1]
plt.plot(x, y)
plt.title("Line Chart")
plt.legend(["Line"])
plt.show()
Output

Simply using plt.plot helped us to create an chart.
2. Bar chart
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:
Python
import matplotlib.pyplot as plt
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
plt.bar(x, y)
plt.title("Bar Chart")
plt.legend(["bar"])
plt.show()
Output

3. Plotting Histogram
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
Python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 4]
plt.hist(x, bins = [1, 2, 3, 4, 5, 6, 7])
plt.title("Histogram")
plt.legend(["bar"])
plt.show()
Output

4. Scatter Plot
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.
Example:
Python
import matplotlib.pyplot as plt
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
plt.scatter(x, y)
plt.legend("A")
plt.title("Scatter chart")
plt.show()
Output

5. Pie Chart
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.
Python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
e =(0.1, 0, 0, 0)
plt.pie(x, explode = e)
plt.title("Pie chart")
plt.show()
Output

You can explore many more plots according to the usecase
7. Stack Plot
Stackplot is used to create stacked area plots. It is a great way to visualize the contributions of multiple categories over time or across other continuous variables. In a stackplot, the areas representing different groups are stacked on top of each other, which allows you to see both individual and cumulative data
Python
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
Studying = [7, 8, 6, 11, 7]
playing = [8, 5, 7, 8, 13]
plt.stackplot(days, Studying, playing, colors =['r', 'c'])
plt.xlabel('Days')
plt.ylabel('No of Hours')
plt.title('Representation of Study and \
Playing wrt to Days')
plt.show()
Output

8. Stem Plot
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
Python
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

9. Box Plot
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.
Python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
data = np.random.normal(100, 20, 200)
fig = plt.figure(figsize =(10, 7))
plt.boxplot(data)
plt.show()
Output

10. Error Plot
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.
Python
import matplotlib.pyplot as plt
x =[1, 2, 3, 4, 5, 6, 7]
y =[1, 2, 1, 2, 1, 2, 1]
y_error = 0.2
plt.plot(x, y)
plt.errorbar(x, y,yerr = y_error,fmt ='o')
Output

11. Violin Plot
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.
Python
import numpy as np
import matplotlib.pyplot as plt
uniform = np.arange(-100, 100)
normal = np.random.normal(size = 100)*30
fig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2,
figsize =(9, 4),
sharey = True)
ax1.set_title('Uniform Distribution')
ax1.set_ylabel('Observed values')
ax1.violinplot(uniform)
ax2.set_title('Normal Distribution')
ax2.violinplot(normal)
plt.show()
Output

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.
Python
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection = '3d')
plt.show()
Output:

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.
Python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
z = [1, 8, 27, 64, 125]
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.plot3D(z, y, x)
plt.show()
Output

Matplotlib Subplot
Subplots are smaller axes (plots) arranged within a single figure allowing users to compare data side by side or stack visualizations for better insights. plt.subplots() method provides an easy way to define the layout of subplots.
Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1)
This syntax creates a figure with nrows rows and ncols columns of subplots.
For more detailed information about Matplotlib Subplot , Refer to the Article Matplotlib subplot
Similar Reads
Introduction
Visualizing data helps us understand and share information more effectively. In Python Matplotlib is one of the best tools for creating visualizations. Itâs powerful, flexible, and lets you make many types of plots, from simple line charts to advanced animations. This tutorial will guide you step by
7 min read
Matplotlib is an overall package for creating static, animated, and interactive visualizations in Python. It literally opens up a whole new world of possibilities for you! Especially when it is used with Numpy or Pandas library, one can do unimaginable things. The plots give may give a new insight a
1 min read
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning,
4 min read
Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert y
4 min read
Pyplot is a submodule of the Matplotlib library in python and beginner-friendly tool for creating visualizations providing a MATLAB-like interface, to generate plots with minimal code. How to Use Pyplot for Plotting?To use Pyplot we must first download the Matplotlib module. For this write the follo
2 min read
Matplotlib is one of the Python packages which is used for data visualization. You can use the NumPy library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is used for making 2D plots from data in arrays. Axes class Axes is the most basic and flexible
4 min read
Working with Legends
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. In this article, we will learn about the Matplotlib Legends. Python Matplotlib.pyplot.legend() SyntaxSyntax: matplotlib.pyplot.legend([
6 min read
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.
2 min read
In this article, we will learn how to Change the legend position in Matplotlib. Let's discuss some concepts : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure
2 min read
Matplotlib is a library for creating interactive Data visualizations in Python. The functions in Matplotlib make it work like MATLAB software. The legend method in Matplotlib describes the elements in the plot. In this article, we are going to Change Legend Font Size in Matplotlib. Using pyplot.lege
3 min read
Prerequisites: Matplotlib In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module.Create data.Change the vertical spacing between label
2 min read
In this article, the task is to use multiple columns in a Matplotlib legend in Python. Before starting the discussion on âUse multiple columns in a Matplotlib legendâ, firstly we should know briefly about matplotlib, pyplot and legend. Matplotlib: The "matplotlib" library basically used to create so
2 min read
The subplot() function in matplotlib helps to create a grid of subplots within a single figure. In a figure, subplots are created and ordered row-wise from the top left. A legend in the Matplotlib library basically describes the graph elements. The legend() can be customized and adjusted anywhere in
3 min read
A legend is basically an area in the plot which describes the elements present in the graph. Matplotlib provides an inbuilt method named legend() for this purpose. The syntax of the method is below : Example: Adding Simple legend C/C++ Code # Import libraries import matplotlib.pyplot as plt # Creati
2 min read
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 th
3 min read
Matplotlib is one of the most popular data visualization libraries present in Python. Using this matplotlib library, if we want to visualize more than a single variable, we might want to explain what each variable represents. For this purpose, there is a function called legend() present in matplotli
5 min read
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 (M
2 min read
Line Chart
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 lin
6 min read
Python is a high-level, interpreted, and dynamically typed programming language that can be used to manage huge datasets. Python supports a wide variety of data visualization libraries like Matplotlib, Seaborn, Bokeh, Geoplotlib, Ggplot, and Plotly. Among all these libraries, Matplotlib is comparati
3 min read
In this article, we will learn how to plot multiple lines using matplotlib in Python. 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
6 min read
In this article, we will learn how to Create the line opacity in Matplotlib. Let's discuss some concepts : A line chart or line graph may be a sort of chart which displays information as a series of knowledge points called âmarkersâ connected by line segments. Line graphs are usually wont to find re
2 min read
Prerequisites: Matplotlib Matplotlib is the most widely used library for plotting graphs with the available dataset. Matplotlib supports line chart which are used to represent data over a continuous time span. In line chart, the data value is plotted as points and later connected by a line to show t
3 min read
With the use of the fill_between() function in the Matplotlib library in Python, we can easily fill the color between any multiple lines or any two horizontal curves on a 2D plane. Syntax: matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs) E
2 min read
Scatter Plot
matplotlib.pyplot.scatter() is used to create scatter plots, which are essential for visualizing relationships between numerical variables. Scatter plots help illustrate how changes in one variable can influence another, making them invaluable for data analysis. A basic scatter plot can be created u
4 min read
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 min read
Prerequisite: Scatterplot using Seaborn in Python Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and
2 min read
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. In this article, we w
3 min read
Prerequisites: Matplotlib Scatter plots are the data points on the graph between x-axis and y-axis in matplotlib library. The points in the graph look scattered, hence the plot is named as 'Scatter plot'. The points in the scatter plot are by default small if the optional parameters in the syntax ar
2 min read
3D Plots
3D plots are very important tools for visualizing data that have three dimensions such as data that have two dependent and one independent variable. By plotting data in 3d plots we can get a deeper understanding of data that have three variables. We can use various matplotlib library functions to pl
6 min read
A 3D Scatter Plot is a mathematical diagram, the most basic version of three-dimensional plotting used to display the properties of data as three variables of a dataset using the cartesian coordinates.To create a 3D Scatter plot, Matplotlib's mplot3d toolkit is used to enable three dimensional plott
2 min read
A Surface Plot is a representation of three-dimensional dataset. It describes a functional relationship between two independent variables X and Z and a designated dependent variable Y, rather than showing the individual data points. It is a companion plot of the contour plot. It is similar to the wi
4 min read
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 libra
1 min read
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look a
2 min read
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
2 min read
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. In this arti
4 min read
Prerequisites: Matplotlib, NumPy In this article, we will see how can we can view our graph from different angles, Here we use three different methods to plot our graph. Before starting let's see some basic concepts of the required module for this objective. Matplotlib is a multi-platform data visua
3 min read
Prerequisites: Matplotlib, NumPy Graphical representations are always easy to understand and are adopted and preferable before any written or verbal communication. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we create a beautiful
4 min read
Working with Images
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. Working with Images in Python using Matplotlib The image module in matplotlib library is
3 min read
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 visua
3 min read
In this article, we are going to depict images using the Matplotlib module in grayscale representation using PIL, i.e. image representation using two colors only i.e. black and white. Syntax: matplotlib.pyplot.imshow(X, cmap=None) Displaying Grayscale image Displaying Grayscale image, store the imag
2 min read
Prerequisites: Matplotlib Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python. ApproachImport modulesRead the imagePlot the line or point on the imageDisplay the plot/image. Image Used: Im
2 min read
Prerequisites: Matplotlib Given an image the task here is to draft a python program using matplotlib to draw a rectangle on it. Matplotlib comes handy with rectangle() function which can be used for our requirement. Syntax: Rectangle(xy, width, height, angle=0.0, **kwargs) Parameters: xy: Lower left
2 min read
The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and vide
2 min read
Let us see how to calculate the area of an image in Python using Matplotlib. Algorithm: Import the matplotlib.pyplot module.Import an image using the imread() method.Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.Calculat
1 min read