Remove whitespace between subplots in a constrained layout (matplotlib)

159 views Asked by At

How to remove the whitespace between the two subplots, while keeping the constrained layout and not using bbox_inches='tight'?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec


df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
plt.rcParams['figure.constrained_layout.use'] = False
fig = plt.figure(layout="constrained")
fig.set_figheight(5)
fig.set_figwidth(5)

gs1 = gridspec.GridSpec(2, 1, figure=fig)

ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1],sharex=ax1)


ax2.table(cellText=df.values, colLabels=df.columns, rowLabels=[
    'Something', '1','2','3','4', '5','6','7','8','9'], loc='center')
ax2.axis('off')
ax1.axes.get_xaxis().set_visible(False)
gs1.update(wspace=0, hspace=0)
plt.show()

Example

2

There are 2 answers

0
Jody Klymak On
fig.get_layout_engine().set(w_pad=0 / 72, h_pad=0 / 72, hspace=0,
                            wspace=0)

almost gets you there:

Small gap

But constrained layout makes room for the "0" in the top axes.

If you want them to touch each other, you can remove the zero:

ax1.set_yticks(np.arange(0.2, 1.1, 0.2))

No gap

You could also make the table an inset_axes:

ax1 = fig.add_subplot(1,1,1)
ax2 = ax1.inset_axes([0, -0.4, 1, 0.4])

But this is a bit of an edged case, where the table needs an extra draw to size properly due to limitations of guessing how big text is before rendering.

fig.draw_without_rendering()

enter image description here

0
Mohammad Golam Dostogir On

I have tried your code and managed to remove the space as per your requirements.

Please try this code below:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

fig = plt.figure(layout="constrained")
fig.set_figheight(5)
fig.set_figwidth(5)

gs1 = gridspec.GridSpec(2, 1, figure=fig)

ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1], sharex=ax1)

ax2.table(cellText=df.values, colLabels=df.columns, rowLabels=[
          'Something', '1', '2', '3', '4', '5', '6', '7', '8', '9'], loc='center')

ax2.axis('off')
ax1.xaxis.set_visible(False)

# Remove the '0' tick from y-axis to prevent space for it
ax1.set_yticks(ax1.get_yticks()[ax1.get_yticks() > 0])

# Adjust the padding of the layout engine to remove any additional space
fig.get_layout_engine().set(w_pad=0 / 72, h_pad=0 / 72, hspace=0, wspace=0)

plt.show()

This will generate the chart like this:

enter image description here

Please note ax1.set_yticks(ax1.get_yticks()[ax1.get_yticks() > 0]), which filters out the '0' tick from the y-axis of the upper plot. Removing the '0' tick reduces the space required for the y-axis ticks.