Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce horizontal subplot spacing when tight_layout fails?

I'm trying to create a single figure in matplotlib with several subplots of different row and column spans, using subplot2grid.

For example, the following code:

import matplotlib.pyplot as plt
import numpy as n

fig = plt.figure()
ax1 = plt.subplot2grid((2, 5), (0, 0), rowspan=2, colspan=2)
ax2 = plt.subplot2grid((2, 5), (0, 2))
ax2_2 = plt.subplot2grid((2, 5), (0, 3))
ax2_3 = plt.subplot2grid((2, 5), (0, 4))
ax3 = plt.subplot2grid((2, 5), (1, 2), colspan=3) #, sharex=ax2)

xs = n.linspace(0, 2*n.pi, 100)
ax1.plot(xs, n.sin(xs))
ax2.plot(xs, n.cos(xs))
ax2_2.plot(xs, n.tan(xs))
ax2_3.plot(xs, n.sin(xs))
ax3.plot(xs, n.cos(xs))


ax2.set_xticklabels([])
ax2.set_yticklabels([])
ax2_2.set_xticklabels([])
ax2_2.set_yticklabels([])
ax2_3.set_xticklabels([])
ax2_3.set_yticklabels([])

# This comes from a separate attempt to make the ticks invisible, but seems to make no change.
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.setp(ax2_2.get_xticklabels(), visible=False)
plt.setp(ax2_2.get_yticklabels(), visible=False)
plt.setp(ax2_3.get_xticklabels(), visible=False)
plt.setp(ax2_3.get_yticklabels(), visible=False)


fig.set_size_inches(6.5, 2.85)
fig.tight_layout()
# I tried several things here - subplots_adjust improves the vertical spacing a little, but not the horizontal.
fig.subplots_adjust(hspace=0.1)

fig.savefig('test.png', dpi=100)

This makes a figure like:

enter image description here

The problem is the 3 single-cell subplots in the top right, each of which has only about 70% of the width that would fit. tight_layout otherwise takes care of the spacing nicely, but I can't work out why this space isn't filled, or how to work around it.

So...does anyone know how to do this, making the subplots take the full available width?

like image 378
inclement Avatar asked Jan 31 '26 15:01

inclement


1 Answers

When using subplots_adjust() the hspace parameter will adjust the vertical space, and the wspace parameter the horizontal space, so perhaps what you need is:

fig.subplots_adjust(wspace=0.1)
like image 116
Saullo G. P. Castro Avatar answered Feb 02 '26 05:02

Saullo G. P. Castro



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!