Matplotlib:如何显示已关闭的图形 [英] Matplotlib: how to show a figure that has been closed

查看:671
本文介绍了Matplotlib:如何显示已关闭的图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数返回用pyplot创建的Figure.此函数在返回图形之前将其关闭.如果我没有关闭它,仅用plt.show()即可显示它很容易,但让我们假设我无法做到这一点.

I have a function which returns a Figure created with pyplot. This function closes the figure before returning it. If I didn't close it, showing it would be very easy with just plt.show(), but let us assume I cannot do that.

我可以轻松地将返回的Figure保存到文件中,但是我找不到显示它的方法(即:弹出窗口显示该图).

I can easily save the returned Figure to a file, but I cannot find the way to display it (i.e.: have a popped window showing the figure).

from matplotlib import pyplot as plt                                                


def new_figure():                                                                   
    fig = plt.figure()                                                              
    plt.plot([0, 1], [2, 3])                                                        
    plt.close(fig)                                                                  
    return fig                                                                      


fig = new_figure()                                                                  
fig.savefig('output.svg')                                                           
fig.show()

我怎么显示这个数字?

推荐答案

figure实例上调用plt.close时,实际上破坏的是图形界面( FigureManager ),用于在屏幕上显示该图(请参见JoeKington在 Matplotlib的评论:重新打开一个封闭的数字?).因此,该图形实例仍然存在并且尚未被销毁.为了再次在屏幕上显示该图,我们必须以某种方式重建一个接口,以替换调用plt.close(fig)时已销毁的接口.

When plt.close is called on a figure instance, what is actually destroyed is the graphical interface (the FigureManager) that is used to show the figure on-screen (see comment by JoeKington at Matplotlib: re-open a closed figure?). So the figure instance still exists and has not been destroyed. To show the figure on-screen again, we would have to reconstruct, in some way, an interface to replace the one that has been destroyed when calling plt.close(fig).

可以通过简单地使用plt.figure()创建一个新图形,窃取"其管理器,并使用它在屏幕上显示我们想要显示的图形来完成此操作.另外,也可以使用GUI Toolkit手动重建一个界面来显示图形.我提供了一个使用Qt4Agg后端 PySide 的示例.此外,这里有一个很好的示例显示了如何使用Tkinter(TkAgg)完成此操作: http: //matplotlib.org/examples/user_interfaces/embedding_in_tk.html (我也测试了这种方法,并且可以使用).

This can be done by simply creating a new figure with plt.figure(), "stealing" its manager, and use it to display the figure that we want to show on-screen. Alternatively, it is possible to reconstruct manually an interface to display the figure with a GUI Toolkit. I provide an example with PySide using the Qt4Agg backend. Moreover, there is a nice example that shows how this can be done with Tkinter (TkAgg) here : http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html (I've tested this approach also and it works).

此解决方案基于通过Matplotlib中的OO接口获取图形管理器.用于构建用于在屏幕上显示图形的图形界面的GUI工具箱取决于后端.如果使用的后端是 TkAgg ,则 TkInter 将在Python 2.7中给出一些可以忽略的警告(请参阅此

This solution is based on how to close a show() window but keep the figure alive? and Obtaining the figure manager via the OO interface in Matplotlib. The GUI toolkit that is used to construct the graphical interface for showing the figure on-screen depends on the backend that is used by matplotlib. If the backend used is TkAgg, TkInter will give some warning in Python 2.7 that can be ignored (see this post on python bug tracker).

import matplotlib.pyplot as plt

def new_figure(): 

    fig = plt.figure()
    plt.plot([0, 1], [2, 3])
    plt.close(fig)
    return fig

def show_figure(fig):

    # create a dummy figure and use its
    # manager to display "fig"

    dummy = plt.figure()
    new_manager = dummy.canvas.manager
    new_manager.canvas.figure = fig
    fig.set_canvas(new_manager.canvas)

if __name__ == '__main__':

    fig = new_figure()
    show_figure(fig)

    plt.show()

Pyside方法:

这包括用新的画布和工具栏重建GUI以在屏幕上显示fig实例.

重要说明:如果从 Spyder ,因为Spyder也是启动它自己的QApplication的Qt应用程序(请参见

Important Note: The code below must be executed in a new dedicated Python console (press F6) if run from Spyder, since Spyder is also a Qt application that starts it's own QApplication (see PySide Qt script doesn't launch from Spyder but works from shell).

import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT
import matplotlib.pyplot as plt

from PySide import QtGui
import sys

def new_figure():

    fig = plt.figure()
    plt.plot([0, 1], [2, 3])
    plt.close(fig)
    return fig   

class myFigCanvas(QtGui.QWidget):

    def __init__(self, fig, parent=None):
        super(myFigCanvas, self).__init__(parent)

        #---- create new canvas and toolbar --

        canvas = FigureCanvasQTAgg(fig)
        toolbar = NavigationToolbar2QT(canvas, self)

        #---- setup layout of GUI ----

        grid = QtGui.QGridLayout()    
        grid.addWidget(canvas, 0, 0)
        grid.addWidget(toolbar, 1, 0)

        self.setLayout(grid)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    fig = new_figure()   
    new_canvas = myFigCanvas(fig) 
    new_canvas.show()    

    sys.exit(app.exec_())

其结果是:

这篇关于Matplotlib:如何显示已关闭的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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