python - 使用 imshow 和 twiny : cannot set xlim

标签 python matplotlib plot imshow

我正在尝试使用 pyplot 绘制图像及其上的一些线条。另外,我需要有两个 x 轴,一个在底部,一个在顶部。假设下面的一个应该有 5 个刻度,范围从 0 到 5,上面的一个也应该有 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()

产生:

enter image description here

但是,一旦我使用 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()

产生:

enter image description here

如何在保持轴上的刻度线对齐的情况下显示图像?

最佳答案

这里有两个相互矛盾的约束:

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

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

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

enter image description here

关于python - 使用 imshow 和 twiny : cannot set xlim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49667468/

相关文章:

python - 在 Python 中,如何创建从现在起 15 分钟后的日期时间? 1小时后?

python - 向 matplotlib/seaborn 图中的某些单元格添加自定义边框

r - 将多个绘图和数据面板导出到 *.png(在 R 中使用布局()样式)

python - 查找最大空闲时间 block

python - 如何检测多个屏幕

python - 如何使用 matplotlib (python) colah 的变形网格进行绘图?

python - 如何使用 Matplotlib 加速绘制大量矩形?

r - 使用 ggplot 和 base plot 函数获得不同的结果

r - ggplot2:代表个人观察的点和代表平均值和标准差的条形图

python - 属性错误: module 'django.db.models' has no attribute 'ManyToMany'