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

Wal*_*l-E 5 plot axis overlay matplotlib imshow

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

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]])
Run Code Online (Sandbox Code Playgroud)

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

顶部:使用 imshow() 的图像。 底部:绘图重叠,图像轴长宽比和大小已更改

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

Imp*_*est 2

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

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

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述