## Place plots side by side in Matplotlib

Python Matplotlib Figure  Luc B.

Python

Matplotlib

When presenting data, it is often helpful to place different plots right next to each other so readers can directly compare. This technique also utilizes figure space more efficiently, making presentations shorter and more concise.

### Code Example

Use the `plt.subplot()` function to divide a figure into multiple plots.

Note that although the code below works fine, Matplotlib's object oriented interface is better suited for creating complex figures. See the second code example below to learn this alternate approach.

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

plt.subplot(121)
# Modify left plot here
plt.title("Left Plot")
plt.text(0.4, 0.4, "1", fontsize=50)

plt.subplot(122)
# Modify right plot here
plt.title("Right Plot")
plt.text(0.4, 0.4, "2", fontsize=50)

plt.show()``````

The argument to `plt.subplot()` is a three digit number. The first digit represents the number of rows, the second digit represents the number of columns, and the third digit represents the current index in the grid.

The grid index starts at 1 and increases from left to right.

For example passing a `221` to `plt.subplot()` creates a figure with 2 rows and 2 columns, and all plotting operations that follow will apply to the plot at coordinate (1, 1). Passing `223` creates a figure with the same divisions, but plotting operations will modify the plot at coordinate (2, 1).

### More Examples

#### Object Oriented Interface

While the pyplot interface used above is convenient, Matplotlib's object oriented interface makes this code more clear and extensible. Use the `plt.subplots()` function to create axes objects for all subplots in the grid.

``````fig, (l, r) = plt.subplots(1, 2)

# Create left axes
l.set_title("Left Plot")
l.text(0.4, 0.4, "1", fontsize=50)

# Create right axes
r.set_title("Right Plot")
r.text(0.4, 0.4, "2", fontsize=50)

plt.show()``````

#### Mutiple Arguments

`plt.subplot()` also supports passing three separate integer arguments instead of one three digit integer.

``````plt.subplot(1, 2, 1)
# Modify left plot here
plt.title("Left Plot")
plt.text(0.4, 0.4, "1", fontsize=50)

plt.subplot(1, 2, 2)
# Modify right plot here
plt.title("Right Plot")
plt.text(0.4, 0.4, "2", fontsize=50)

plt.show()``````