How can I set the visual width of one subplot equal to the width of another subplot using Python and Matplotlib? The first plot has a fixed aspect ratio and square pixels from i
The two existing answers at the time of this writing are helpful, but do not provide a solution. A solution follows. The key used here, not in the other answers, is to access the spine
locations directly. plt.draw()
is required to update the coordinates before accessing them.
import numpy as np
from matplotlib import pyplot as plt
im = np.arange(256).reshape(16,16)
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(211)
ax.imshow(im)
plt.show()
transAxes = ax.transAxes
invFig = fig.transFigure.inverted()
llx,urx = plt.xlim()
lly,ury = plt.ylim()
llx0, lly0 = transAxes.transform((0,0))
llx1, lly1 = transAxes.transform((1,1))
plt.draw()
spleft = ax.spines['left'].get_verts()
spright = ax.spines['right'].get_verts()
llx0 = spleft[0,0]
llx1 = spright[0,0]
axp = invFig.transform(((lly0,llx0),(lly1,llx1)))
ax2 = fig.add_axes([axp[0,1],axp[0,0]-0.5,axp[1,1]-axp[0,1],axp[1,0]-axp[0,0]])
ax2.plot(np.arange(10))
plt.draw()