matplotlib:在同一轴上使用plot和imshow时的限制

2024-09-29 21:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试着把椭圆画成imshow图。它可以工作,但是在绘制图像之后绘制椭圆似乎会增加xlim和ylim,从而产生一个边框,我想去掉这个边框:

请注意,仅在调用imshow之后没有白色边框。

我的代码如下:

self.dpi = 100
self.fig = Figure((6.0, 6.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setMinimumSize(800, 400)
self.cax = None
self.axes = self.fig.add_subplot(111)
self.axes.imshow(channel1, interpolation="nearest")
self.canvas.draw()
self.axes.plot(dat[0], dat[1], "b-")

我试过在调用“plot”前后设置限制,但没有效果

# get limits after calling imshow
xlim, ylim = pylab.xlim(), pylab.ylim()
...
# set limits before/after calling plot
self.axes.set_xlim(xlim)
self.axes.set_ylim(ylim)

如何强制绘图不增加现有的图形限制?

解决方案(感谢Joe):

#for newer matplotlib versions
self.axes.imshow(channel1, interpolation="nearest")
self.axes.autoscale(False)
self.axes.plot(dat[0], dat[1], "b-")

#for older matplotlib versions (worked for me using 0.99.1.1)
self.axes.imshow(channel1, interpolation="nearest")
self.axes.plot(dat[0], dat[1], "b-", scalex=False, scaley=False)

Tags: selfplotfigdat边框canvassetimshow
1条回答
网友
1楼 · 发布于 2024-09-29 21:27:08

正在发生的是轴正在自动缩放以匹配绘制的每个项目的范围。图像的自动缩放比直线等要紧得多(imshow基本上称为ax.axis('image'))。

得到之前和之后的轴限制应该已经工作。(不过,之前和之后只做limits = axes.axis()会更干净。)

但是,如果不想自动缩放,最好在初始绘图后关闭自动缩放。在绘制图像后尝试axes.autoscale(False)

例如,比较一下:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.imshow(np.random.random((10,10)))
ax.plot(range(11))
plt.show()

enter image description here


有了这个:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.imshow(np.random.random((10,10)))
ax.autoscale(False)
ax.plot(range(11))
plt.show()

enter image description here

相关问题 更多 >

    热门问题