Skip to content Skip to sidebar Skip to footer

How To Use Sharex And Sharey Combined With Aspect=equal And Adjustable='box-forced' To Create Subplots With The Same Scale In Matplotlib?

I'm trying to create four subplots, whose axes represent different range of distances [km] in different directions, except for the x-axis of the lower right subplot that represents

Solution 1:

You want to change the underlying grid to have the plots have different sizes. The different limits would act as the ratio between the sizes of the grid cells.

You then still need to adjust the figure size to have nice spacings and set the aspect of the last subplots which is different from 1.

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

lim1 = [0.,30.]
lim2 = [0.,15.]
lim3 = [0.,75.]
lim4 = [0,5]
xdat = [12.,25.]
ydat = [6.,12.]
zdat = [50.,25.]
cdat = [1,1]

gskw = dict(width_ratios = [np.diff(lim1)[0],np.diff(lim3)[0]],
            height_ratios= [np.diff(lim2)[0],np.diff(lim3)[0]])

gs = matplotlib.gridspec.GridSpec(2,2, **gskw)

fig = plt.figure(figsize=(6,5))

ax1=fig.add_subplot(gs[0,0], aspect="equal",adjustable='box-forced')
ax1.plot(xdat,ydat,'o')

ax2=fig.add_subplot(gs[0,1], aspect="equal",adjustable='box-forced', sharey=ax1)
ax2.plot(zdat,ydat,'o') 

ax3=fig.add_subplot(gs[1,0], aspect="equal",adjustable='box-forced', sharex=ax1)
ax3.plot(xdat,zdat,'o')

asp, = np.diff(lim4)/np.diff(lim3)
ax4=fig.add_subplot(gs[1,1], aspect=asp)
ax4.plot(cdat,zdat,'o')

ax1.set_xlim(lim1)
ax1.set_ylim(lim2)
ax2.set_xlim(lim3)
ax3.set_ylim(lim3)
ax4.set_xlim(lim4)
ax4.set_ylim(lim3)

plt.show()

enter image description here

Post a Comment for "How To Use Sharex And Sharey Combined With Aspect=equal And Adjustable='box-forced' To Create Subplots With The Same Scale In Matplotlib?"