2012-02-02 123 views
21

我一直在試圖將一個橢圓繪製到imshow圖中。它的工作原理,但圖像繪製之後繪製橢圓似乎增加XLIM和ylim,導致邊界,我想它擺脫:matplotlib:在同一軸上使用plot和imshow時的限制

注意,有直接NO白色邊框僅在調用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-") 

我已經嘗試過,並呼籲「暗算」後設置的限制,沒有效果

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

我怎麼能強迫情節不增加現有數字限制?

解決方案(感謝喬):

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

回答

29

發生了什麼事是,軸自動縮放,以匹配每一個項目,你圖的範圍。圖像自動縮放比線等要緊得多(imshow基本上稱爲ax.axis('image'))。

之前獲取軸極限值並設置它們應該已經工作。 (雖然之前只做limits = axes.axis()axes.axis(limits)之後更乾淨。)

但是,如果您不想自動縮放,最好在初始繪圖之後關閉自動縮放。繪製圖像後嘗試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

+3

喬您好,感謝您的詳細EXP lanation!我的matplotlib版本似乎太舊了(matplotlib .__ version__ ='0.99.1.1'),因爲它既不支持plt.subplots()也不支持ax.autoscale,但是當您指出autoscale = False時,我發現了[替代解決方案]( http://stackoverflow.com/questions/7386872/make-matplotlib-autoscaling-ignore-some-of-the-plots)修復了我的問題:每次我在最初調用imshow之後使用plot時,我都使用關鍵字參數scalex =假,scaley = False,這是正確的!謝謝! – soramimo 2012-02-03 20:30:22