How do you show multiple graphs in python?

In this Python Matplotlib tutorial, we’ll discuss the Matplotlib multiple plots in python. Here we will cover different examples related to the multiple plots using matplotlib. Moreover, we’ll also cover the following topics:

  • Matplotlib multiple plots
  • Matplotlib multiple plots example
  • Matplotlib multiple plots one title
  • Matplotlib multiple plots one legend
  • Matplotlib plot multiple rectangles
  • Matplotlib multiple plots one colorbar
  • Matplotlib multiple polar plots
  • Matplotlib multiple boxplot
  • Matplotlib multiple violin plots
  • Matplotlib multiple circle plots
  • Matplotlib multiple contour plots
  • Matplotlib multiple plots histogram
  • Matplotlib multiple plots seaborn

Matplotlib’s subplot[] and subplots[] functions facilitate the creation of a grid of multiple plots within a single figure. Multiple pots are made and arranged in a row from the top left in a figure.

subplot[] function

The syntax for subplot[] function is as given below:

matplotlib.pyplot.subplot[nrows, ncols, index, **kwargs]

                             #OR

matplotlib.pyplotsubplot[pos, **kwargs]

The parameters are as follow:

  • nrows: Specifies the number of rows.
  • ncols: Specifies the number of columns.
  • index: Specifies the index of the current plot.
  • kwargs: Specifies the extra features to glorify the plots.
  • pos: Specifies the position of the current plot.

In the first syntax, we pass three separate integers arguments describing the position of the multiple plots.

In the second syntax, we pass a three-digit integer to specify the positional argument to define nrows, ncols, and index.

subplots[] function

The syntax for subplots[] function is as given below:

matplotlib.pyplot.subplots[nrows, ncols, sharex=False, 
                           sharey=False, squeeze=True,  
                           subplot_kw=None, gridspec_kw=None, 
                           **kwargs]

The parameters are as follow:

  • nrows, ncols: Specify the number of rows and columns.
  • sharex, sharey: Specify the sharing properties among the x-axis and y-axis.
  • squeeze: The default value for this optional parameter is True, and it normally contains boolean values.
  • subplot_kw: The dict with keywords provided to the add subplot method, which is used to create each subplot.
  • gridspec_kw: It is used to create the grid on which multiple plots are located.

subplot[] vs subplots[]

While using the subplots[] function you can use just one line of code to produce a figure with multiple plots. On the other hand, the subplot[] function only constructs a single subplot ax at a given grid position.

Also, check Matplotlib subplots_adjust

Matplotlib multiple plots example

Here we’ll see an example of multiple plots using matplotlib functions subplot[] and subplots[].

Let’s see examples:

Example #1

In this example, we’ll use the subplot[] function to create multiple plots.

# Import library

import matplotlib.pyplot as plt

# Create figure


fig = plt.figure[]

# Create each subplot individually


ax1 = plt.subplot[131]
ax2 = plt.subplot[132]
ax3 = plt.subplot[133]

# Auto adjust


plt.tight_layout[]

# Display

plt.show[]
  • Firstly, we import matplotlib.pyplot library for creating plots.
  • Then, we create a figure using the figure[] function.
  • After this, we create multiple plots individually using the subplot[] function.
  • Then, we use the tight_layout[] function to auto-adjust the layout of multiple plots.
  • To display the figure, we use the show[] function.

Matplotlib multiple plots example

Example #2

In this example, we’ll use the subplots[] function to create multiple plots.

# Import library


import matplotlib.pyplot as plt

# Create figure and multiple plots

fig, axes = plt.subplots[nrows=2, ncols=2]

# Auto adjust


plt.tight_layout[]

# Display

plt.show[]
  • Import matplotlib.pyplot as plt for graph creation.
  • Then, we call the subplots[] function with the figure along with the subplots that are then stored in the axes array.
  • Here we create multiple plots with 2 rows and 2 columns.
  • To adjust the layout of the multiple plots, we use the tight_layout[] function.
  • To display the figure, we use the show[] function.

Example of matplotlib multiple plots

Read: Matplotlib increase plot size

Matplotlib multiple plots one title

Here we’ll learn to add one title or we can say that common title on multiple plots using matplotlib. The suptitle[] function is used to add a centered title to the figure.

Let’s see examples related to this:

Example #1

In this example, we use the subplot[] function to draw multiple plots, and to add one title use the suptitle[] function.

# Import library


import matplotlib.pyplot as plt

# Create figure

fig = plt.figure[]

# Define Data Coordinates

x = range[5]
y = range[5]

# Create each subplot individually


plt.subplot[2, 2, 1]
plt.plot[x, y, linestyle='dashed', color='r']
plt.subplot[2, 2, 2]
plt.plot[x, y, linestyle='dashdot', color='green']
plt.subplot[2, 2, 4]
plt.plot[x, y, linestyle='dotted', color='m']

# One Title


plt.suptitle['Different Line Plots']

# Auto adjust

plt.tight_layout[]

# Display


plt.show[]
  • Import matplotlib.pyplot library for data plotting.
  • Then, we create a figure using the figure[] method.
  • To define x and y data coordinates, use the range[] function of python.
  • Then, we create multiple plots individually using the subplot[] function.
  • To plot a line chart between data coordinates, use the plot[] function with linestyle and color parameters.
  • To add a one title on the multiple plots, use the suptitle[] function.
  • To adjust the spacing between multiple plots, use the tight_layout[] function.
  • To display the figure, use the show[] function.

Matplotlib multiple plots one title

Example #2

In this example, we use the subplots[] function to draw multiple plots, and to add one title use the suptitle[] function.

# Import library

import matplotlib.pyplot as plt

# Create figure and multiple plots

fig, ax = plt.subplots[nrows=2, ncols=1]

# Define Data

x = range[15]
y = range[15]

# Plot


ax[0].plot[x, y, color='r']
ax[1].bar[x, y, color='green']

# Title

plt.suptitle['Multiple Plots With One Title', 
              fontweight='bold']

# Auto adjust

plt.tight_layout[]

# Display

plt.show[]
  • Import necessary library matplotlib.pyplot.
  • After this, use the subplots[] function to create a figure with multiple plots.
  • To define data coordinates, use the range[] method of python.
  • To draw the first plot, we use the plot[] function.
  • To plot a second plot, we use the bar[] function.
  • To add one title, we use the suptitle[] function of matplotlib.
  • To display a figure, we use the show[] function.

Matplotlib multiple plots with one title

Read: What is add_axes matplotlib

Matplotlib multiple plots one legend

In matplotlib, the legend is used to express the graph elements. We can set and adjust the legends anywhere in the plot. Sometimes, it is requisite to create a single legend with multiple plots.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Create figure


fig = plt.figure[figsize=[10, 9]]

# Multiple Plots

axes = fig.subplots[nrows=1, ncols=2]

# Define Data


year = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
        2009, 2010]
birth_rate = [26.635, 26.170, 25.704, 25.238, 24.752, 24.266, 
              23.779, 23.293, 22.807, 22.158, 21.508]
death_rate = [8.804, 8.661, 8.518, 8.375, 8.261, 8.147, 8.034, 
              7.920, 7.806, 7.697, 7.589]

# Plot

axes[0].plot[year,birth_rate, label='Birth Rate', marker='o']
axes[1].plot[year,death_rate ,label='Death Rate', marker='o']

# Legend

handels = []
labels = []
  
for ax in fig.axes:
    Handel, Label = ax.get_legend_handles_labels[]
    handels.extend[Handel]
    labels.extend[Label]
    
fig.legend[handels, labels, loc = 'upper center']

# Display

plt.show[]
  • Import matplotlib.pyplot library for data visualization.
  • Then, we create a figur using figure[] method.
  • To create multiple plots , we use subplots[] function.
  • Next, we define data coordinates.
  • Then, we use plot[] function to plot a line graph.
  • After this, we create two empty list defining handels and labels.
  • If there are more lines and labels in a single subplot, the list extend function is used to add them all to the lines and labels list.
  • To show the legend, we use legend[] function.
  • To display the plot, we use the show[] function.

Matplotlib multiple plots one legend

Recommendation: Matplotlib scatter plot legend

Matplotlib plot multiple rectangles

In matplotlib, the patches module allows us to overlay shapes such as rectangles on top of a plot. The Rectangle[] function in the patches module can be used to add a rectangle.

The Rectangle function takes the width and height of the rectangle you need, as well as the left and bottom positions. The rectangle highlights the specific portion of the plot as we needed.

The syntax to plot rectangle is given below:

matplotlib.patches.Rectangle[xy, width, height, 
                             angle=0.0,**kwargs]

The above-used parameters are defined below:

  • xy: Specify the anchor point i.e. lower left point where the rectangle starts.
  • width: Specify the width of the rectangle.
  • height: Specify the height of the rectangle.
  • angle: Specify the angle of rotation of the rectangle.

Let’s see examples related to this:

Example #1

In this example, we plot multiple rectangles to highlight the highest and lowest weight and height.

# Import Libraries


import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches
  • Firstly, we import necessary libraries such as
    • matplotlib.pyplot for data visualization.
    • pandas for data creation.
    • matplotlib.patches to add shapes like rectangles on top of a plot.
# Load Dataset

df = pd.read_csv['weight-height.csv']

We will use the weight-height dataset and load it directly from the CSV file.

Click here to download the dataset:

# Print Top 10 Rows

df.head[10]

# Print Last 10 Rows

df.tail[10]

df.head[]

df.tail[]

# Set figure size

plt.figure[figsize=[10,7]]

# Plot scatter graph

plt.scatter[x=df.Height, y=df.Weight]

# Add Labels

plt.xlabel["Height",fontweight ='bold', size=14]
plt.ylabel["Weight", fontweight ='bold',size=14]
  • To set the size of the plot, we use the figure[] method to pass the figsize parameter and set its width and height.
  • To plot a scatter graph, we use the scatter[] method.
  • To add the label at the x-axis, we use xlabel[] function.
  • To add the label at the y-axis, we use ylabel[] function.
  • To glorify the labels at axes, we pass fontweight and size as parameters.
# Define coordinates of rectangle 1

left, bottom, width, height = [73, 225, 8, 55]

# Plot Rectangle 1

rect=mpatches.Rectangle[[left,bottom],width,height,
                        alpha=0.1,
                        facecolor="green"]
# Add Rectangle 1

plt.gca[].add_patch[rect]

# Define coordinates of rectangle 2

left, bottom, width, height = [52, 50, 8, 48]

# Plot Rectangle 2

rect=mpatches.Rectangle[[left,bottom],width,height, 
                        alpha=0.3,
                        facecolor="yellow"]

# Add Rectangle 2

plt.gca[].add_patch[rect]

# Display

plt.show[]
  • We define the coordinates of the rectangle x, y, width, and height.
  • By using the Rectangle[] function, we can add a rectangle.
  • The Rectangle function takes the position, size, facecolor, and alpha as parameters.
  • To add this rectangle object to an already existing plot, we use the gca[] function to get the current axis.
  • Using the add_patch[] function, place the rectangle on top of the plot.
  • To display the figure, we use the show[] function.

Plot multiple rectangles using matplotlib

Example #2

In this example, we plot multiple rectangles to highlight the weight and height range according to the minimum and maximum BMI index.

# Import Libraries

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches

Import necessary libraries for defining data coordinates and plotting graph and rectangle patches.

# Load Dataset
df = pd.read_csv['bmi.csv']

Next, we load the dataset using read_csv[] function.

Click here to download the dataset:

# Print Top 10 Rows

df.head[10]

# Print Last 10 Rows

df.tail[10]

df.head[]

df.tail[]

# Set figure size

plt.figure[figsize=[10,7]]

# Plot scatter graph

plt.scatter[x=df.Index, y=df.Height]
plt.scatter[x=df.Index, y=df.Weight]

# Add Labels

plt.xlabel["BMI INDEX",fontweight ='bold', size=14]
plt.ylabel["WEIGHT[kg] / HEIGHT[cm]", 
            fontweight ='bold',size=14]
  • To increase the size of the figure, we use the figure[] method and pass figsize parameter to it with the width and height of the plot.
  • To plot a graph, we use the scatter[] function.
  • To set labels at axes, we use xlabel[] and ylabel[] functions.
# Define coordinates of rectangle 1

left, bottom, width, height = [-0.09, 45, 0.2, 20]

# Plot Rectangle 1

rect=mpatches.Rectangle[[left,bottom],width,height,
                        alpha=0.1,
                        facecolor="c"]
# Add Rectangle 1

plt.gca[].add_patch[rect]



# Define coordinates of rectangle 2

left, bottom, width, height = [-0.09, 161, 0.2, 40]

# Plot Rectangle 2

rect=mpatches.Rectangle[[left,bottom],width,height, 
                        alpha=0.3,
                        facecolor="yellow"]

# Add Rectangle 2

plt.gca[].add_patch[rect]



# Define coordinates of rectangle 3

left, bottom, width, height = [4.91, 76, 0.2, 86]

# Plot Rectangle 3

rect=mpatches.Rectangle[[left,bottom],width,height,
                        alpha=0.1,
                        facecolor="red"]
# Add Rectangle 3

plt.gca[].add_patch[rect]



# Define coordinates of rectangle 4

left, bottom, width, height = [4.91, 160, 0.2, 40]

# Plot Rectangle 4

rect=mpatches.Rectangle[[left,bottom],width,height, 
                        alpha=0.1,
                        facecolor="green"]

# Add Rectangle 4

plt.gca[].add_patch[rect]



# Display

plt.show[]
  • The x, y, width, and height coordinates of the rectangle are defined.
  • We can add a rectangle by using the Rectangle[] function.
  • Position, size, facecolor, and alpha are all arguments for the Rectangle function.
  • We call the gca[] function to fetch the current axis in order to add this rectangle object to an already existing plot.
  • Place the rectangle on top of the plot using the add_patch[] function.
  • The show[] function is used to display the figure.

Plot multiple rect using matplotlib

Here we use the rectangles to highlight the range of weight and height corresponding to the minimum and maximum index of BMI.

Read: Matplotlib time series plot

Matplotlib multiple plots one colorbar

Here we’ll learn to add one colorbar for multiple plots in the figure using matplotlib.

Let’s see examples:

Example #1

In this example, we use a different dataset to plots multiple charts with one colorbar.

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np
 
# Define Data

data_x = np.linspace[-20, 30, 3000]
data_y = np.linspace[-50, 20, 3000]

# Meshgrid

X, Y = np.meshgrid[data_x, data_y]

Z1 = 5*X + 2*Y
Z2 = X - Y
Z3 = X*Y + 2
Z4 = X**5+Y**5
 
# Create a figure object

fig, axes = plt.subplots[2, 2,
                         figsize=[8,8],constrained_layout=True]

# Plot 

im_1 = axes[0,0].imshow[Z1, cmap='seismic']
im_2 = axes[0,1].imshow[Z2, cmap='seismic']
im_3 = axes[1,0].imshow[Z3, cmap='seismic']
im_4 = axes[1,1].imshow[Z4, cmap='seismic']

# Colorbar

color_bar = fig.colorbar[im_1, ax=axes[:, 1], shrink=0.5]

# Display

plt.show[]
  • Import necessary libraries such as matplotlib.pyplot and numpy.
  • Then, we define data coordinates using linspace[] function.
  • After this, we also define meshgrid using meshgrid[] function.
  • To create a subplot, we use subplots[] function.
  • Then, we plot a graph using the imshow[] function.
  • To add a color bar to the plot, we use the colorbar[] function.
  • To display the plot, we use the show[] function.

Matplotlib multiple plots one colorbar

Example #2

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt

# Define Subplots


fig, axes = plt.subplots[3, 2,
                        figsize=[8,8],constrained_layout=True]

# Define Plots

for ax in axes.flat:
    im = ax.imshow[np.random.random[[30,30]],cmap='BrBG']

# Define Colorbar Coordinates


color_bar = fig.add_axes[[1, 0.15, 0.05, 0.7]]

# Colorbar plot

fig.colorbar[im, cax=color_bar]

# Display

plt.show[]
  • Import matplotlib.pyplot library for data visualization.
  • Import numpy for data creation.
  • To create multiple plots, we use the subplots[] function.
  • To iterate all the axes, we use axes.flat.
  • To define data coordinates, use random.random[] function of numpy.
  • To plot a graph, we use the imshow[] function.
  • After this, we set axes of the color bar using the add_axes[] function.
  • To add a color bar to the plot, use the colorbar[] function.

Matplotlib multiple plots single colorbar

Here we create 6 multiple plots with 3 rows and 2 columns with one colorbar.

Also, check: Matplotlib scatter plot color

Matplotlib multiple polar plots

Here we’ll learn to create multiple polar plots using matplotlib. To add an Axes to the figure as part of multiple plots, we use the add_subplot[] method of the matplotlib library’s figure module.

Let’s take an example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
import math

# Create new figure 

fig  = plt.figure[figsize=[6, 6]]

# Set the title of the polar plot

plt.suptitle['Multiple Polar Plots']

# Create first subplot

fig.add_subplot[221, projection='polar']

# Define Data

radius = np.arange[0, [5*np.pi], 0.05]
r = 4

# Plot

for radian in radius: 
    plot.polar[radian, r,'o']

# Create second subplot

fig.add_subplot[222, projection='polar']

# Define Data


a = 4
b = 3

# Plot

for radian in radius:
    r = [a*b]/math.sqrt[[a*np.cos[radian]]**2 + 
                        [b*np.tan[radian]]**2]  
    plt.polar[radian,r,'o'] 
    
# Create third subplot


fig.add_subplot[223, projection='polar']

# Define Data

a = 8

# Plot

for radian in radius:
    r = a + [a*np.sin[radian]]  
    plt.polar[radian,r,'o'] 
    
# Create fourth subplot


fig.add_subplot[224, projection='polar']

# Define Data

a = 1
n = 10

# Plot

for radian in radius:
    r = a * np.cos[n*radian]  
    plt.polar[radian,r,'o']   

# Auto adjust layout 


plt.tight_layout[] 

# Display the Polar plot

plt.show[]
  • Import necessary libraries, such as matplotlib.pyplot, numpy, and math.
  • To increase the size of the figure, use figure[] method and pass figsize parameter with width and height to it.
  • To add a single title on the multiple plots, use suptitle[] function.
  • To create multiple plots, use add_subplot[] function.
  • To set projection to polar, we pass projection parameter to add_subplot[] function.
  • Next, we define data coordinates.
  • To plot a polar graph, we use polar[] function.
  • To auto adjust the layout of the figure, we use tight_layout[] function.
  • To display the figure, we use show[] function.

Matplotlib multiple polar plots

Read: Matplotlib tight_layout – Helpful tutorial

Matplotlib multiple boxplot

Here we’ll learn to plot multiple boxplots with the help of an example using matplotlib.

Let’s see an example:

# Import Libraries

import matplotlib.pyplot as plt
import pandas as pd
import random
  • Firstly, import all the necessary libraries such as:
    • matplotlib.pyplot for data visualization.
    • pandas for data creation.
    • random for accessing the random numbers.
# Create figure and axes

fig, ax = plt.subplots[2,2, figsize=[8,6]] 
  • plt.subplots[] is a function that returns a tuple containing a figure, and axes object.
  • We define 2 rows and 2 columns.
  • To increase the size of the figure, we pass figsize parameter to the method.
  • We set the width of the plot to 8 and the height of the plot to 6.
# Define Data

data_frame = pd.DataFrame[data={
               'Group 1': random.sample[range[60, 200], 10],
               'Group 2': random.sample[range[20, 80], 10],
               'Group 3': random.sample[range[2000, 3060], 10],
               'Category':list[2*'A']+list[4*'B']+list[4*'C']
                }]
  • Then, we create a data frame using DataFrame[] function.
  • We define data using random.sample[] and range[] functions.
  • We also define categories using list[] function to create a list object.
# Plot boxplot

for i,elist in enumerate[list[df.columns.values][:-1]]:
    box_plot = df.boxplot[elist, by="Category",  
                          ax=axes.flatten[][i]]
  • The method enumerate[] adds a counter to an iterable and returns it as an enumerating object.
  • This enumerated object can then be used in loops directly or converted to a list of tuples with the list[] method.
  • To plot a boxplot chart, we use boxplot[] function.
  • axes.flatten[] is method of the numpy array. Instead of an iterator, it returns a flattened version of the array.
# Remove Empty Subplot

fig.delaxes[axes[1,1]]

# Auto adjust multiple plots

plt.tight_layout[] 

# Display figure

plt.show[]
  • To remove empty plot, we use the delaxes[] function.
  • To auto adjust the layout of the plots, we use the tight_layout[] function.
  • To display the figure, we use the show[] function.

Matplotlib multiple boxplot

Read: Matplotlib update plot in loop

Matplotlib multiple violin plots

Violin plots combine the features of a box plot and a histogram. Data distributions are visualized using violin plots, which show the data’s range, median, and distribution.

The following is the syntax:

matplotlib.axes.Axes.violinplot[dataset, positions=None, 
                                vert=True, width=0.5, 
                                showmeans=False, 
                                showextrema=True, 
                                showmedians=False, 
                                quantiles=None, points=100,  
                                bw_method=None, *, data=None]

Here we’ll see an example of multiple violin plots:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Create figure and multiple plots


fig, ax = plt.subplots[2,3, figsize=[8,6]] 

# Define Data

np.random.seed[30]
data_1 = np.random.normal[100, 10, 200]
data_2 = np.random.normal[80, 30, 200]
data_3 = np.random.normal[90, 20, 1200]
data_4 = np.random.normal[70, 25, 2000]
data_5 = np.random.normal[270, 325, 400]


# Create the boxplot

ax[0,0].violinplot[data_1]
ax[0,1].violinplot[data_2]
ax[0,2].violinplot[data_3]
ax[1,0].violinplot[data_4]
ax[1,2].violinplot[data_5]

# Remove empty plot

fig.delaxes[ax[1,1]]

# Auto layout

plt.tight_layout[]

# Display

plt.show[]
  • Firstly, we import matpltlib.pyplot module for data visualization.
  • Next, we import numpy library as np for data defining or creation.
  • Then, we create a new figure and multiple plots using subplots[] method.
  • We create 2 rows with 3 plots in each.
  • By using figsize argument, we modify the figure size.
  • Next, we use random.seed[] function to generate random numbers with same seed value on mltiple executions of the code.
  • Then, we use random.normal[] function to generates a sample of numbers drawn from the normal distribution.
  • To plot violin plot, we call violinplot[] function with different axes.
  • To remove the empty plot at 1st row and 1st column, we use delaxes[] function.
  • To auto adjust the layout of the plot, we use tight_layout[] function.
  • To visualize the plot on user’s screen, we use show[] method.

Matplotlib multiple violin plots

Read: Matplotlib Pie Chart Tutorial

Matplotlib multiple circle plots

In matplotlib, the patches module allows us to overlay shapes such as circles on top of a plot. The Circle[] function in the patches module can be used to add a circle.

The Circle function takes the center of the circle you need, as well as the radius. The circle patches are also used to highlights the specific portion of the plot as we needed.

The following is the syntax:

matplotlib.patches.Circle[xy, radius ,**kwargs]

Let’s see an example related to multiple circle plots:

# Import Library


import matplotlib.pyplot as plt 

# Create subplot and figure

fig, ax = plt.subplots[2,2, figsize=[8,8]] 

# Plot circles

circle_1 = plt.Circle[[ 0.4 , 0.4],0.35, color='r']
circle_2 = plt.Circle[[ 0.5 , 0.5 ], 0.4 , color='yellow', 
                      alpha=0.2]
circle_3 = plt.Circle[[ 0.45 , 0.5 ], 0.2 , fill=False]

# Add Circle Patch
 
ax[0,0].add_artist[ circle_1 ]
ax[0,1].add_artist[ circle_2 ]
ax[1,1].add_artist[ circle_3 ] 

# Add title on each plot

ax[0,0].set_title['Colored Circle']
ax[0,1].set_title['Transparent Circle']
ax[1,1].set_title['Outlined Circle']

# Main Title

plt.suptitle[ 'Multiple Circle Plots',fontweight='bold',fontsize=18 ]

# Remove empty plot

fig.delaxes[ax[1,0]]

# Display

plt.show[]
  • Import matplotlib.pyplot library for data visulaization.
  • Here we create multiple plots in 2 rows and 2 columns using subplots[] function.
  • To set the size of the figure, we pass figsize argument to the method.
  • To plot a circle, we use Circle[] function.
  • Place the circle on top of the plot using the add_patch[] function.
  • To add title on each plot, we use set_title[] method.
  • To add a main title to the figure, we use suptitle[] function.
  • To remove an emoty plot, we use delaxes[] function.
  • To display a plot, we use show[] function.

Matplotlib multiple circle plots

Matplotlib multiple contour plots

Contour plots, also known as level plots, are a multivariate analytic tool that allows you to visualize 3-D plots in 2-D space. Contour plots are commonly used in meteorological departments to illustrate densities, elevations, or mountain heights.

The matplotlib contour[] function is used to draw contour plots.

The following is the syntax:

matplotlib.pyplot.contour[[X, Y, ] Z, [levels], **kwargs]

Let’s see an example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Create a figure object and multiple plots

fig, ax = plt.subplots[2,2, figsize=[6,6]]
 
# Define Data

data_x = np.linspace[-20, 30, 3000]
data_y = np.linspace[-50, 20, 3000]

# Meshgrid

X, Y = np.meshgrid[data_x, data_y]

Z1 = np.cos[X/2] + np.sin[Y/4]
Z2 = X*Y + 2
Z3 = X - Y
Z4 = np.cos[X/2] + np.tan[Y/4]

# Countor Plot

ax[0,0].contour[X, Y, Z1]
ax[0,1].contour[X, Y, Z2]
ax[1,0].contour[X, Y, Z3]
ax[1,1].contour[X, Y, Z4]

# Display

plt.show[]
  • Import matplotlib.pyplot and numpy libraries.
  • To create multiple plots, we use subplots[] function.
  • To define data coordinates, we use linspace[], meshgrid[], cos[], sin[], tan[] functions.
  • To plot countor plots, we use contour[] function.
  • To display the figure, we use show[] function.

Matplotlib multiple contour plots

Example #2

Here we will use the contourf[] function which draws the filled contours. We use the same data set defined in the above example.

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Create a figure object

fig, ax = plt.subplots[2,2, figsize=[6,6]]
 
# Define Data

data_x = np.linspace[-20, 30, 3000]
data_y = np.linspace[-50, 20, 3000]

# Meshgrid

X, Y = np.meshgrid[data_x, data_y]
Z1 = np.cos[X/2] + np.sin[Y/4]
Z2 = X*Y + 2
Z3 = X - Y
Z4 = np.cos[X/2] + np.tan[Y/4]

# Countor Plot

ax[0,0].contourf[X, Y, Z1]
ax[0,1].contourf[X, Y, Z2]
ax[1,0].contourf[X, Y, Z3]
ax[1,1].contourf[X, Y, Z4]

# Display

plt.show[]

The only difference between this and the first example is that we call the contourf[] method.

Matplotlib multiple plots contour

Read: Matplotlib multiple bar chart

Matplotlib multiple plots histogram

Here we’ll learn to plot multiple histogram graphs with the help of examples using matplotlib.

Example:

# Import library


import matplotlib.pyplot as plt
import numpy as np


# Create figure and multiple plots

fig, ax = plt.subplots[2,2,figsize=[8,6]]

# Define Data

x = np.random.normal[loc=1, size=50000]
y = np.random.normal[loc=-1, size=10000]
z = np.random.randn[10000, 3]

# Plot

ax[0,0].hist[x, bins=80, color='r']
ax[0,1].hist[y, bins=50, alpha=0.5, 
             color='green',histtype='step']
ax[1,1].hist[z, bins=20, alpha=0.5, color=
            ['green','yellow','orange'],histtype='bar']

# Remove empty plot

fig.delaxes[ax[1,0]]

# Auto adjust

plt.tight_layout[]

# Display

plt.show[]
  • Import matplotlib.pyplot library.
  • To create multiple plots, we use subplots[] function.
  • To define the data for plotting, we use random.normal[] and random.randn[] functions.
  • To plot a histogram graph, we use hist[] function.
  • We also define different type of histogram types using histtype argument.
  • To remove empty plot, we use delaxes[] function.

Matplotlib multiple plots histogram

Read: Stacked Bar Chart Matplotlib

Matplotlib multiple plots seaborn

Here we’ll learn to draw multiple seaborn plots using matplotlib.

Let’s see an example:

# Import Libraries

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
 
# Seaborn Style

sns.set[]

# Create new figure and plots

fig, ax = plt.subplots[1,2]

# Define Data


x = range[15]
y = range[15]

# Plot

ax[0].plot[x, y, color='r']
ax[1].bar[x, y, color='green']

# Auto layout

plt.tight_layout[]

# Display

plt.show[]
  • Import necessary libraries such as
    • matplotlib.pyplot for data visualization.
    • seaborn for data visualization.
    • numpy for data creation.
  • Then we set default style of seaborn using sns.set[] function.
  • To create subplots, we use subplots[] function with 1 row and 2 columns.
  • To define data coordinates, we use range[] function.
  • To plot a graphs, we use plot[] and bar[] functions.
  • To auto adjsut the layout of multiple plots, we use tight_layout[] function.
  • To display the figure, we use show[] function.

Matplotlib multiple plots seaborn

Also, take a look at some tutorials on Matplotlib.

  • Matplotlib default figure size
  • Matplotlib bar chart labels
  • Matplotlib not showing plot
  • Put legend outside plot matplotlib
  • Matplotlib savefig blank image

In this Python tutorial, we have discussed the “Matplotlib multiple plots” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib multiple plots
  • Matplotlib multiple plots example
  • Matplotlib multiple plots one title
  • Matplotlib multiple plots one legend
  • Matplotlib plot multiple rectangles
  • Matplotlib multiple plots one colorbar
  • Matplotlib multiple polar plots
  • Matplotlib multiple boxplot
  • Matplotlib multiple violin plots
  • Matplotlib multiple circle plots
  • Matplotlib multiple contour plots
  • Matplotlib multiple plots histogram
  • Matplotlib multiple plots seaborn

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

How do you display multiple plots in python?

Matplotlib multiple contour plots.
Import matplotlib. pyplot and numpy libraries..
To create multiple plots, we use subplots[] function..
To define data coordinates, we use linspace[], meshgrid[], cos[], sin[], tan[] functions..
To plot countor plots, we use contour[] function..
To display the figure, we use show[] function..

How do you plot multiple graphs on different figures in Python?

Managing multiple figures in pyplot.
import matplotlib.pyplot as plt import numpy as np t = np. arange[0.0, 2.0, 0.01] s1 = np. sin[2*np. pi*t] s2 = np. sin[4*np. ... .
figure[1] plt. subplot[211] plt. plot[t, s1] plt. subplot[212] plt. plot[t, 2*s1].
figure[1] plt. subplot[211] plt. plot[t, s2, 's'] ax = plt. gca[] ax..

How do you plot 3 graphs side by side in Python?

To create multiple plots we use the subplot function of pyplot module in Matplotlib. Parameters: nrows is for number of rows means if the row is 1 then the plots lie horizontally. ncolumns stands for column means if the column is 1 then the plot lie vertically.

How do I show multiple figures in Matplotlib?

Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”..
Draw a line using plot[] method, over the current figure..
Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”..
Draw a line using plot[] method, over the current figure..

Chủ Đề