How to modify the navigation toolbar easily in a matplotlib figure window?

前端 未结 6 1308
暖寄归人
暖寄归人 2020-11-30 04:05

Is it possible to do something like the following to modify the navigation toolbar in matplotlib?

  1. Generate a figure window, with: fig = figure()
6条回答
  •  无人及你
    2020-11-30 05:01

    With MPL 1.2.1 it is possible to get an handler of the navigation toolbar of a standard MPL figure through figure.canvas.toolbar. I'm not sure about previous versions.

    At least with the QT backend it is possible to add arbitrary widgets to the navigation toolbar using the QT method .addWidget(). I suppose other backends will work using similar methods, but I haven't tested them.

    Here it is a working example (using the QT backend) that adds a QLineEdit() to the navigation toolbar to change the title of a MPL figure (run from IPython (pylab) with run -i ..., then launch test()):

    from PySide import QtGui, QtCore
    
    def test():
        plot([1,2,3], lw=2)
        q = qt4_interface(gcf())
        return q   # WARNING: it's paramount to return the object otherwise, with 
                   # no references, python deletes it and the GUI doesn't respond!
    
    class qt4_interface:
        def __init__(self,fig):
            self.fig = fig
    
            toolbar = fig.canvas.toolbar
            self.line_edit = QtGui.QLineEdit()
            toolbar.addWidget(self.line_edit)
            self.line_edit.editingFinished.connect(self.do_something) 
    
        def do_something(self, *args):
            self.fig.axes[0].set_title(self.line_edit.text())
            self.fig.canvas.draw()
            #f = open('l','a'); f.write('yes\n'); f.flush(); f.close()
    

提交回复
热议问题