本文介绍了matplotlib:在同一轴上使用plot和imshow时的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将一个椭圆绘制成一个imshow图.它可以工作,但是在绘制图像后再绘制椭圆似乎会增加xlim和ylim,从而产生一个边框,我想摆脱它:

I've been trying to plot an ellipse into an imshow plot. It works, but plotting the ellipse after plotting the image seems to increase xlim and ylim, resulting in a border, which I'd like to get rid of:

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

Note that there is NO white border directly after calling imshow only.

我的代码如下:

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-")

我尝试在调用绘图"之前和之后设置限制,但没有效果

I've tried setting the limits before and after calling "plot", with no effect

# 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)

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

How can I force plot not to increase existing figure limits?

解决方案(感谢乔):

#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)

推荐答案

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

What's happening is that the axis is autoscaling to match the extents of each item you plot. Images are autoscaled much tighter than lines, etc (imshow basically calls ax.axis('image')).

应该先获取轴限制,然后再设置轴限制. (不过,仅在limits = axes.axis()之前和axes.axis(limits)之后执行比较干净.)

Getting the axis limits before and setting them after should have worked. (It's cleaner to just do limits = axes.axis() before and axes.axis(limits) after, though.)

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

However, if you don't want things to autoscale, it's best to just turn autoscaling off after the initial plot. Try axes.autoscale(False) after plotting the image.

作为一个例子,比较一下:

As an example, compare this:

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()

与此:

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()

这篇关于matplotlib:在同一轴上使用plot和imshow时的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:28