2014-03-29 42 views
4

當使用matplotlib:matplotlib秀的身影再次出現

from matplotlib import pyplot as plt 

figure = plt.figure() 

ax = figure.add_subplot(111) 
ax.plot(x,y) 

figure.show() # figure is shown in GUI 

# How can I view the figure again after I closed the GUI window? 

figure.show() # Exception in Tkinter callback... TclError: this isn't a Tk application 
figure.show() # nothing happened 

所以我的問題是:

  1. 我怎樣才能獲得以前的情節回來,如果我呼籲figure.show()?

  2. 如果我有多個數字,並且因此from pylab import *; plot(..); show()似乎不是我正在尋找的解決方案,是否有更方便的替代figure.add_suplot(111)

而我急切地想爲

showfunc(stuff) # or 
stuff.showfunc() 

其中stuff是包含排列在一個畫面中的所有情節的對象,showfunc是無狀態的(我的意思是,每次我把它的時候,我的行爲就好像它第一次被調用一樣)。這與matplotlib一起使用可能嗎?

+0

目前尚不清楚問題出在哪裏。你指的是以前的情節? – ebarr

+0

@ebarr我的意思是,如何在關閉GUI窗口後再次查看圖形?再次創建一個'figure'和'plot'?我認爲應該有更好的方式來做到這一點。 –

+0

因此'show'只能在腳本中運行一次,因爲它啓動Tk mainloop運行。該文檔稱「v1.0.0中的新增功能:show now現在只有在它尚未運行時纔會啓動GUI主循環,因此現在允許多個顯示調用。」你能否添加一些關於你需要什麼功能的信息?你在建立一個圖形用戶界面嗎?或者你只是想一個接一個地看看情節? – ebarr

回答

2

我無法找到一個滿意的答案,所以我寫延伸matplotlib.figure.Figure定製Figure類,並提供了新的show()方法,它創建一個gtk.Window對象每次調用時處理這個問題。

import gtk 
import sys 
import os 
import threading 

from matplotlib.figure import Figure as MPLFigure 
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas 
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NaviToolbar 


class ThreadFigure(threading.Thread): 
    def __init__(self, figure, count): 
     threading.Thread.__init__(self) 
     self.figure = figure 
     self.count = count 
    def run(self): 
     window = gtk.Window() 
     # window.connect('destroy', gtk.main_quit) 

     window.set_default_size(640, 480) 
     window.set_icon_from_file(...) # provide an icon if you care about the looks 

     window.set_title('MPL Figure #{}'.format(self.count)) 
     window.set_wmclass('MPL Figure', 'MPL Figure') 

     vbox = gtk.VBox() 
     window.add(vbox) 

     canvas = FigureCanvas(self.figure) 
     vbox.pack_start(canvas) 

     toolbar = NaviToolbar(canvas, window) 
     vbox.pack_start(toolbar, expand = False, fill = False) 

     window.show_all() 
     # gtk.main() ... should not be called, otherwise BLOCKING 


class Figure(MPLFigure): 
    display_count = 0 
    def show(self): 
     Figure.display_count += 1 
     thrfig = ThreadFigure(self, Figure.display_count) 
     thrfig.start() 

將該文件作爲開頭文件IPython。並且

figure = Figure() 
ax = figure.add_subplot(211) 
... (same story as using standard `matplotlib.pyplot`) 
figure.show() 

# window closed accidentally or intentionally... 

figure.show() 
# as if `.show()` is never called 

工程!我從來沒有觸及過GUI編程,也不知道這是否會有任何副作用。如果你認爲應該這樣做,應該自由評論。

+0

這必須是最有用的matplotlib變通辦法之一我曾經遇到過。做好這個解決方案。走出神祕的Tcl/Tk窗口系統並進入Gtk確實是一種解放,並通過線程解決了許多其他相關的matplotlib misbehaviours。 – venzen