Place plots side by side in Matplotlib
Last Updated :
09 Aug, 2022
Matplotlib is the most popular Python library for plotting graphs and visualizing our data. In Matplotlib we can create multiple plots by calling them once. To create multiple plots we use the subplot function of pyplot module in Matplotlib.
Syntax: plt.subplot(nrows, .ncolumns, index)
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.
- and index is the count/index of plots. It starts with 1.
Approach:
- Import libraries and modules.
- Create data for plot.
- Now, create a subplot using above function.
- Give the parameters to the function according to the requirement.
Example 1:
Python3
import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 ])
y_1 = 2 * x
y_2 = 3 * x
plt.subplot( 1 , 2 , 1 )
plt.plot(x, y_1, 'r' , linewidth = 5 , linestyle = ':' )
plt.title( 'FIRST PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.subplot( 1 , 2 , 2 )
plt.plot(x, y_2, 'g' , linewidth = 5 )
plt.title( 'SECOND PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.tight_layout( 4 )
plt.show()
|
Output:
Example 2: In vertical form.
Python3
import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 ])
y_1 = 2 * x
y_2 = 3 * x
plt.subplot( 2 , 1 , 1 )
plt.plot(x, y_1, 'r' , linewidth = 5 , linestyle = ':' )
plt.title( 'FIRST PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.subplot( 2 , 1 , 2 )
plt.plot(x, y_2, 'g' , linewidth = 5 )
plt.title( 'SECOND PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.tight_layout()
plt.show()
|
Output:
To increase the size of the plots we can write like this
plt.subplots(figsize(l, b))
Example 3:
Python3
import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 ])
y_1 = 2 * x
y_2 = 3 * x
plt.subplots(figsize = ( 15 , 5 ))
plt.subplot( 1 , 2 , 1 )
plt.plot(x, y_1, 'r' , linewidth = 5 , linestyle = ':' )
plt.title( 'FIRST PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.subplot( 1 , 2 , 2 )
plt.plot(x, y_2, 'g' , linewidth = 5 )
plt.title( 'SECOND PLOT' )
plt.xlabel( 'x-axis' )
plt.ylabel( 'y-axis' )
plt.tight_layout( 4 )
plt.show()
|
Output:
Share your thoughts in the comments
Please Login to comment...