How to make your Matplotlib plot display correctly using Python

2 min

Most of the time, your plot won't display correctly.

This is because you add stuff on them and the chart ends up needing to be rearranged.

Matplotlib provides us with a clean way to do exactly that.

The .tight_layout() method.

It will try to fit all your plots nicely in the figure.

Here is what a badly fitted plot can look like
Here is what we aim for

Here is the code

# To plot it
import matplotlib.pyplot as plt

# We generate our data
x = range(10)

# We create our canvas
fig, axes = plt.subplots(2,

# We plot a line plot
axes[0][0].plot(x, x)
axes[0][0].set_title("plot 1")
axes[0][0].set_xlabel("x labels")
axes[0][0].set_ylabel("x labels")

# We plot our second plot onto the figure
axes[0][1].plot(x, x)
axes[0][1].set_title("plot 2")
axes[0][1].set_xlabel("x labels")
axes[0][1].set_ylabel("x labels")

# We plot our third plot onto the figure
axes[1][0].plot(x, x)
axes[1][0].set_title("plot 3")
axes[1][0].set_xlabel("x labels")
axes[1][0].set_ylabel("x labels")

# We plot our fourth plot onto the figure
axes[1][1].plot(x, x)
axes[1][1].set_title("plot 4")
axes[1][1].set_xlabel("x labels")
axes[1][1].set_ylabel("x labels")

# Here we tidy up the figure

# We show the plot

As you can see, the plot is well fitted to the figure which is what we were aiming for.

Here you are! You now know how to make your plot display correctly with Matplotlib using Python.

More on Matplotlib

If you like what you've just read and want to know more about the Matplotlib library (e.g. how to add labels, plot different types of plots, etc...) check out the other articles I wrote on the topic, just here :

Matplotlib - The Python You Need
We gathered the only Python essentials that you will probably ever need.