python logo

subplot python


Python hosting: Host, run, and code Python in the cloud!

Matplotlib’s subplot() function is a versatile tool for creating multiple plots within a single figure. This function supports various arrangements of plots, including vertical (2x1), horizontal (1x2), and grid layouts (e.g., 2x2).
If you’re keen to expand your data visualization skills with Matplotlib in Python, consider exploring the Data Visualization with Matplotlib and Python course.

Horizontal Subplot

The following code demonstrates how to set up a horizontal subplot using Matplotlib:

1
2
3
4
5
6
7
8
9
10
11
12
from pylab import *
t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
subplot(2,1,1)
xticks([]), yticks([])
title('subplot(2,1,1)')
plot(t,s)
subplot(2,1,2)
xticks([]), yticks([])
title('subplot(2,1,2)')
plot(t,s,'r-')
show()

Horizontal subplot with Matplotlib

Vertical Subplot

You can adjust the subplot parameters to achieve a vertical layout. Here’s how:

1
2
3
4
5
6
7
8
9
10
11
12
from pylab import *
t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
subplot(1,2,1)
xticks([]), yticks([])
title('subplot(1,2,1)')
plot(t,s)
subplot(1,2,2)
xticks([]), yticks([])
title('subplot(1,2,2)')
plot(t,s,'r-')
show()

Vertical subplot with Matplotlib

Grid Layout with Subplots

For a grid layout of plots (e.g., 2x2), utilize the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from pylab import *
t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
subplot(2,2,1)
xticks([]), yticks([])
title('subplot(2,2,1)')
plot(t,s)
subplot(2,2,2)
xticks([]), yticks([])
title('subplot(2,2,2)')
plot(t,s,'r-')
subplot(2,2,3)
xticks([]), yticks([])
title('subplot(2,2,3)')
plot(t,s,'g-')
subplot(2,2,4)
xticks([]), yticks([])
title('subplot(2,2,4)')
plot(t,s,'y-')
show()

2x2 grid layout subplot with Matplotlib

Navigate through our visualization tutorials using the links below:
Previous Tutorial | Next Tutorial






Leave a Reply: