Home > database >  Problem with Matplotlib subplots with different number of rows and columns
Problem with Matplotlib subplots with different number of rows and columns

Time:10-11

The code below creates a 4x4 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?)

CodePudding user response:

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

CodePudding user response:

You should adjust the figsize:

_, axs = plt.subplots(rows, cols, figsize=(5, 5./2))
  • Related