How to Create Multiple Subplots in Matplotlib in Python? Last Updated : 16 Jan, 2024 Comments Improve Suggest changes Like Article Like Report To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with the objects Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid. By default, it returns a figure with a single plot. For each axes object i.e. plot we can set a title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()). Let’s see how this works: When we call the subplots() method by stacking only in one direction it returns a 1D array of axes objects i.e. subplots. We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding Create Multiple Subplots in Matplotlib in Python Here, we have various Ways to Matplotlib create subplots in Python. Here, we are using some generally used Ways to Matplotlib create subplots in Python those are following. 1-D Array of Subplots Using Stacking in Two Directions Using plt.subplots with 2D Array of Subplots Subplots in Matplotlib Using 1-D Array of Subplots In this example code utilizes Matplotlib to generate a figure with two subplots. The data, represented by arrays ‘x,’ ‘y,’ and ‘z,’ is plotted on separate axes within the figure. The resulting visualization displays distinct plots for the datasets ‘y’ and ‘z’ in the designated subplots. Python3 # importing library import matplotlib.pyplot as plt # Some data to display x = [1, 2, 3] y = [0, 1, 0] z = [1, 0, 1] # Creating 2 subplots fig, ax = plt.subplots(2) # Accessing each axes object to plot the data through returned array ax[0].plot(x, y) ax[1].plot(x, z) Output Subplots in Matplotlib Using Stacking in Two Directions In this Python script, the Matplotlib library is imported, and NumPy is used for numerical operations. Data for plotting sine waves is generated. The script then creates a 3×2 grid of subplots, each plotting the same sine wave with different colors (orange, green, blue, magenta, black, and red). Python3 # importing library import matplotlib.pyplot as plt import numpy as np # Data for plotting x = np.arange(0.0, 2.0, 0.01) y = 1 + np.sin(2 * np.pi * x) # Creating 6 subplots and unpacking the output array immediately fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2) ax1.plot(x, y, color="orange") ax2.plot(x, y, color="green") ax3.plot(x, y, color="blue") ax4.plot(x, y, color="magenta") ax5.plot(x, y, color="black") ax6.plot(x, y, color="red") Output Subplots_fig2 Matplotlib Multiple Plots Same Figure In this example Python script utilizes Matplotlib to create a 2×2 grid of subplots. Each subplot showcases a different type of plot: line plot, scatter plot, bar plot, and histogram. The Axes objects are accessed through the 2D array ‘axs,’ and specific data is visualized in each subplot, demonstrating the flexibility of Matplotlib for diverse plotting needs. Python3 import matplotlib.pyplot as plt # Create a 2x2 grid of subplots fig, axs = plt.subplots(2, 2) # Now axs is a 2D array of Axes objects axs[0, 0].plot([1, 2, 3], [4, 5, 6]) axs[0, 1].scatter([1, 2, 3], [4, 5, 6]) axs[1, 0].bar([1, 2, 3], [4, 5, 6]) axs[1, 1].hist([1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5]) plt.show() Output Comment More info Advertise with us Next Article How to Add Title to Subplots in Matplotlib? T tejalkadam18m Follow Improve Article Tags : Python Python-matplotlib Practice Tags : python Similar Reads Introduction Matplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It 5 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 Jupyter Notebook is a free, open-source web app that lets you create and share documents with live code and visualizations. It is commonly used for tasks like cleaning and transforming data, doing statistical analysis, creating visualizations and machine learning. Matplotlib is a popular Python libr 2 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 Multiple Plots To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with the objects Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid. By default, it returns a figure with a single 3 min read In this article, we will see how to add a title to subplots in 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 3 min read A title in Matplotlib library describes the main subject of plotting the graphs. Setting a title for just one plot is easy using the title() method. By using this function only the individual title plots can be set but not a single title for all subplots. Hence, to set a single main title for all su 2 min read In this article, we are going to discuss how to turn off the axes of subplots using matplotlib module. We can turn off the axes for subplots and plots using the below methods: Method 1: Using matplotlib.axes.Axes.axis() To turn off the axes for subplots, we will matplotlib.axes.Axes.axis() method he 2 min read In this article, we will learn different ways to create subplots of different sizes using Matplotlib. It provides 3 different methods using which we can create different subplots of different sizes. Methods available to create subplot: Gridspecgridspec_kwsubplot2gridCreate Different Subplot Sizes in 4 min read Let's learn how to set the spacing between the subplots in Matplotlib to ensure clarity and prevent the overlapping of plot elements, such as axes labels and titles. Let's create a simple plot with the default spacing to see how subplots can sometimes become congested. [GFGTABS] Python import numpy 3 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 Legends helps to understand what each element in the plot represents. They help to understand the meaning behind different elements like colors, markers or line styles. If a plot contains many labels a single-column legend may: Take up too much vertical spaceOverlap with the plot andLook messy or cl 3 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 A legend helps explain the elements in a plot, and for adding a legend to a plot in Matplotlib, we use the legend() function. A border is added by default to the legend, but there may be some cases when you will prefer not having a border for a cleaner appearance. We will demonstrate how to do it qu 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 Line plots are important data visualization elements that can be used to identify relationships within the data. Using matplotlib.pyplot.plot() function we can plot line plots. Styling tools in this helps us customize line plots according to our requirements which helps in better representations. Li 4 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 Changing Line Opacity in Matplotlib means adjusting the transparency level of a line in a plot. Opacity controls how much the background or overlapping elements are visible through the line. A fully opaque line is solid, while a more transparent line allows other elements behind it to be seen. Let's 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 Bar Plot A bar plot uses rectangular bars to represent data categories, with bar length or height proportional to their values. It compares discrete categories, with one axis for categories and the other for values. Consider a simple example where we visualize the sales of different fruits: [GFGTABS] Python 5 min read Matplotlib is the standard python library for creating visualizations in Python. Pyplot is a module of Matplotlib library which is used to plot graphs and charts and also make changes in them. In this article, we are going to see how to draw a horizontal bar chart with Matplotlib. Creating a vertica 2 min read In this article, we will learn how to Create a stacked bar plot 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 wi 3 min read A Stacked Percentage Bar Chart is a simple bar chart in the stacked form with a percentage of each subgroup in a group. Stacked bar plots represent different groups on the top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It go 3 min read In this article, we will learn how to plot back-to-back bar charts in 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 d 2 min read 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 2 min read Annotation means adding notes to a diagram stating what values do it represents. It often gets tiresome for the user to read the values from the graph when the graph is scaled down or is overly populated. In this article, we will discuss how to annotate the bar plots created in python using matplotl 3 min read A Barplot is a graph that represents the relationship between a categoric and a numeric feature. Many rectangular bars correspond to each category of the categoric feature and the size of these bars represents the corresponding value. Using grouped bar plots, we can study the relationship between mo 3 min read Histogram Histograms are a fundamental tool in data visualization, providing a graphical representation of the distribution of data. They are particularly useful for exploring continuous data, such as numerical measurements or sensor readings. This article will guide you through the process of Plot Histogram 6 min read The histogram is a graphical representation of data. We can represent any kind of numeric data in histogram format. In this article, We are going to see how to create a cumulative histogram in Matplotlib Cumulative frequency: Cumulative frequency analysis is the analysis of the frequency of occurren 2 min read Creating the histogram provides the visual representation of data distribution. By using a histogram we can represent a large amount of data and its frequency as one continuous plot. How to plot a histogram using Matplotlib For creating the Histogram in Matplotlib we use hist() function which belong 3 min read Histograms are a way of visualizing the data. Here, we will learn how to plot overlapping histograms in python using Matplotlib library. matplotlib.pyplot.hist() is used for making histograms. Let's take the iris dataset and plot various overlapping histograms with Matplotlib. Step 1: Import the lib 2 min read Prerequisites: Matplotlib A histogram is a graphical representation of the distribution of data given by the user. Its appearance is similar to Bar-Graph except it is continuous. The towers or bars of a histogram are called bins. The height of each bin shows how many values from that data fall into 4 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 Pie Chart 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 in Python are widely used in business presentations, reports, and dashboards due to their simplicity and effectiveness in displaying data d 8 min read 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 wed 3 min read 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 u 3 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 that visualizes data points in three dimensions, allowing us to observe relationships between three variables of a dataset. Matplotlib provides a built-in toolkit called mplot3d, which enables three-dimensional plotting. To create a 3D Scatter Plot, we use 4 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 Like