Problem with Matplotlib subplots with different number of rows and columns

Question:

The code below creates a 4×4 grid of plots as expected:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
rows, cols = 4, 4
_, axs = plt.subplots(rows, cols, figsize=(5,5))
for i in range(rows):
    for j in range(cols):
        axs[i,j].plot(x,x)

4x4

But things go wrong when I try to display subplots with 2 rows and 4 columns (same code with rows, cols = 2, 4):

2x4 result

When I would expect something like this:

2x4 expected

If I try to add axs[i,j].set_aspect('equal', 'box') after each plot, I get:

2x4 meh

Which is somehow better, but still leaves an empty line, just as if the default "tall rectangle" figure was leaving its footprint. Overall I have the impression that matplotlib wants its subplots to look "square-y".

Before I look into complicated layout matters, does anybody know about some straightforward way to come up with the result I’m expecting (which is not so crazy to expect, right?)

Asked By: Pierrick Bruneau

||

Answers:

You are decreasing the rows, but keeping the figure the same size. You would need to adjust the figsize. So since you cut the rows in half, cut the height in half too to stay proportional.

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
rows, cols = 2, 4
_, axs = plt.subplots(rows, cols, figsize=(5, 2.5))
for i in range(rows):
    for j in range(cols):
        axs[i,j].plot(x,x)

enter image description here

Answered By: chitown88

You should adjust the figsize:

_, axs = plt.subplots(rows, cols, figsize=(5, 5./2))
Answered By: Adrian Usler
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.