Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with Matplotlib subplots with different number of rows and columns

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading