Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlibplot: How to add space between some subplots

Tags:

matplotlib

How can I adjust the whitespace between some subplots? In the example below, let's say I want to eliminate all whitespace between the 1st and 2nd subplots as well as between the 3rd and 4th and increase the space between the 2nd and 3rd?

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ax = plt.subplots(4,figsize=(10,10),sharex=True)

ax[0].plot(x, y)
ax[0].set_title('Panel: A')

ax[1].plot(x, y**2)

ax[2].plot(x, y**3)
ax[2].set_title('Panel: B')
ax[3].plot(x, y**4)

plt.tight_layout() 
like image 470
user5121229 Avatar asked Dec 18 '22 23:12

user5121229


1 Answers

To keep the solution close to your code you may use create 5 subplots with the middle one being one forth in height of the others and remove that middle plot.

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ax = plt.subplots(5,figsize=(7,7),sharex=True, 
                     gridspec_kw=dict(height_ratios=[4,4,1,4,4], hspace=0))

ax[0].plot(x, y)
ax[0].set_title('Panel: A')

ax[1].plot(x, y**2)

ax[2].remove()

ax[3].plot(x, y**3)
ax[3].set_title('Panel: B')
ax[4].plot(x, y**4)


plt.tight_layout()
plt.show()

enter image description here

like image 95
ImportanceOfBeingErnest Avatar answered Feb 16 '23 19:02

ImportanceOfBeingErnest