# Python Matplotlib – Creating subplots

In this post we will be creating subplots in Python using the Matplotlib library. The subplot function will enable us to have multiple plots on a single figure, this can be useful when wanting plot data in various types or plotting more than one pieces of data.

In this example we will be making us of the following data samples.

``````X = [1,2,3,4,5,6,7,8,9,10]
Y1 = [55,66,69,72,85,92,101,116,102,95]
Y2 = [42,54,62,69,72,75,83,87,91,98]
Y3 = [21,31,35,45,47,52,64,72,82,90]
Y4 = [2,6,8,7,5,9,11,16,14,19]``````

Our subplot function will take three pieces of input which consist of the number of rows in the figure, the number of columns and finally the plot order. These can be separated by a comma or placed next to each other without a comma.

See the code below as an example. The figure consist of one row with four columns and we see the order incremented by one each time.

``````import matplotlib.pyplot as plt

X = [1,2,3,4,5,6,7,8,9,10]
Y1 = [55,66,69,72,85,92,101,116,102,95]
Y2 = [42,54,62,69,72,75,83,87,91,98]
Y3 = [21,31,35,45,47,52,64,72,82,90]
Y4 = [2,6,8,7,5,9,11,16,14,19]

plt.figure(figsize=(8, 3))

plt.subplot(1,4,1)
plt.scatter(X, Y1)

plt.subplot(1,4,2)
plt.bar(X, Y2)

plt.subplot(1,4,3)
plt.stem(X, Y3)

plt.subplot(1,4,4)
plt.step(X, Y4)

plt.suptitle('Subplot chart')
plt.show()``````

The code above would return the following as output.

If you were wanting to change the number of rows to two instead, you could use the following. Notice here we are not using the commas to separate our input.

``````import matplotlib.pyplot as plt

X = [1,2,3,4,5,6,7,8,9,10]
Y1 = [55,66,69,72,85,92,101,116,102,95]
Y2 = [42,54,62,69,72,75,83,87,91,98]
Y3 = [21,31,35,45,47,52,64,72,82,90]
Y4 = [2,6,8,7,5,9,11,16,14,19]

plt.figure(figsize=(8, 3))

plt.subplot(221)
plt.scatter(X, Y1)

plt.subplot(222)
plt.bar(X, Y2)

plt.subplot(223)
plt.stem(X, Y3)

plt.subplot(224)
plt.step(X, Y4)

plt.suptitle('Subplot chart')
plt.show()
``````

The code above would return the following as output.