matplotlib:在同一轴上使用 plot 和 imshow 时的限制 [英] matplotlib: limits when using plot and imshow in same axes

查看:30
本文介绍了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-")

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

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?

解决方案(感谢 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)

推荐答案

发生的事情是轴正在自动缩放以匹配您绘制的每个项目的范围.图像的自动缩放比线条等更紧密(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.

举个例子,对比一下:

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 时的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆