Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the subplots in the subfigures getting smaller?

I am using gridspec within a subfigure. For some reason matshow plots are getting smaller and smaller.

import numpy as np
import matplotlib.pyplot as plt

mask = np.array([
        [ 1, 0, 1, 0, 1],
        [ 1, 1, 1, 1, 1],
        [ 0, 0, 0, 0, 0],
        [ 1, 1, 1, 1, 1],
        [ 1, 1, 1, 1, 0]
])   
    
fig = plt.figure(figsize = (12,16), layout = "constrained")
figures = fig.subfigures(4, 2)
figures = figures.reshape(-1)
x = np.linspace(0, 1, 100)
y = x**(0.5)

for f in figures:
    spec = f.add_gridspec(3, 2)
    for i in range(3):
        image_axis = f.add_subplot(spec[i, 0])
        image_axis.matshow(mask, cmap = 'grey')
    plot_axis = f.add_subplot(spec[:,1])
    plot_axis.plot(x, y)

plt.savefig('test.png')

enter image description here

like image 333
Todd Sierens Avatar asked Oct 31 '25 14:10

Todd Sierens


1 Answers

This is an annoyance with constrained layout. However, the easiest solution is to nest the subfigures yet again:

import numpy as np
import matplotlib.pyplot as plt

mask = np.array([
        [ 1, 0, 1, 0, 1],
        [ 1, 1, 1, 1, 1],
        [ 0, 0, 0, 0, 0],
        [ 1, 1, 1, 1, 1],
        [ 1, 1, 1, 1, 0]
])

fig = plt.figure(figsize = (12,16), layout = "constrained")
figures = fig.subfigures(4, 2)
figures = figures.reshape(-1)
x = np.linspace(0, 1, 100)
y = x**(0.5)

for f in figures:
    subsubfigs = f.subfigures(1, 2)
    imaxs = subsubfigs[0].subplots(3, 1)
    for i in range(3):

        imaxs[i].matshow(mask, cmap = 'grey')
    plot_axis = subsubfigs[1].subplots(1, 1)
    plot_axis.plot(x, y)

plt.savefig('test.png')

This frees the left-hand columns from being tied to the right-hand columns. Note that you will likely prefer some spacing between the subfigures, but presumably you were going to add labels etc.

enter image description here

like image 57
Jody Klymak Avatar answered Nov 03 '25 03:11

Jody Klymak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!