Skip to main content
 首页 » 编程设计

python之使用 imshow 和 twiny : cannot set xlim

2024年09月07日7dflying

我正在尝试使用 pyplot 在图像上绘制一些线条。另外,我需要两个 x 轴,一个在底部,一个在顶部。假设下面的那个应该有五个刻度,范围从 0 到 5,上面的那个也应该有五个刻度,但范围从 36 到 41,并且这些刻度应该对齐。这很容易通过以下方式完成:

from matplotlib import pyplot as plt 
 
fig, ax1 = plt.subplots() 
ax1.axis([0,5,10,20])      # set bottom axis limits 
plt.grid() 
ax2 = plt.twiny() 
ax2.axis([36,41,10,20])    # set top axis limits 
plt.show() 

产生:

但是,一旦我使用 imshow,我似乎无法正确设置底部 x 轴的限制:

import numpy as np 
from matplotlib import pyplot as plt 
# Using a small checkerboard as image 
a = np.array([[0,1],[1,0]]) 
fig, ax1 = plt.subplots() 
ax1.axis([0,5,10,20])     # Set lower axis limits -> are ignored 
ax1.imshow(a, extent=(0,5,10,20)) 
plt.grid() 
ax2 = plt.twiny()         # If these two lines are commented 
ax2.axis([36,41,10,20])   # imshow behaves as expected 
plt.show() 

产生:

如何在显示图像的同时保持坐标轴上的刻度线对齐?

请您参考如下方法:

这里有两个矛盾的约束:

  • 为轴设置的限制。
  • 图像的等长宽比。

你可以放松其中之一,即如果你想指定限制,使方面自动,

ax1.imshow(a, extent=(0,5,10,20), aspect="auto")