Matplotlib 在 imshow 上绘图,同时保持轴大小

Matplotlib plot over imshow while keeping axis size

每当我使用 imshow() 绘制图像时,在双底部 x 轴上绘制一维数据会更改使用 imshow() 创建的初始 x 轴的大小和纵横比.我如何避免这种行为?以下是重现问题的方法:

import numpy as np
import matplotlib
matplotlib.use('macosx')
import matplotlib.pyplot as plt

im = np.random.rand(2856, 4290)
light_curve = im[1000, :]

fig = plt.figure(1, figsize=(10,10))
ax1 = plt.subplot(2,1,1)
ax1.imshow(im, cmap='gray', origin='lower')
ax2 = plt.subplot(2,1,2)
ax2.imshow(im, cmap='gray', origin='lower')
# Setting aspect ratio to equal does not help
ax2.set_aspect('equal')

ax21 = ax2.twinx()
ax21.plot(light_curve, alpha=0.7)
# Setting axis limits does not help
ax1.axis([0, im.shape[1], 0, im.shape[0]])
ax21.set_xlim([0, im.shape[1]])

这是我的图形后端的样子(macosx,如果有任何相关性的话)

上面使用 twinx() 的目的不就是首先帮助解决这个问题吗? 那么,我如何才能保持初始 imshow() x 轴固定,并让 1D 图的后续轴简单地适合,而不调整大小或弄乱纵横比,而无需完全手动构建我的轴?

确实有点不幸的是,方面没有传播到双轴,因为它周围有相同的框。

我认为解决这个问题的唯一方法是手动计算纵横比并将其设置为双轴。

import numpy as np
import matplotlib.pyplot as plt

im = np.random.rand(285, 429)
light_curve = im[100, :]

fig = plt.figure(1, figsize=(8,8))
ax1 = plt.subplot(2,1,1)
ax1.imshow(im, cmap='gray', origin='lower')
ax2 = plt.subplot(2,1,2)

ax2.imshow(im, cmap='gray', origin='lower')
ax2.set_aspect("equal", "box-forced")

ax21 = ax2.twinx()

ax21.plot(light_curve, alpha=0.7)
# Setting axis limits does not help
ax21.set_xlim(ax1.get_xlim())

a = np.diff(ax21.get_ylim())[0]/np.diff(ax1.get_xlim())*im.shape[1]/im.shape[0]
ax21.set_aspect(1./a, "box-forced")

plt.show()