如何通过matplotlib API创建带有show()的图形?

时间:2013-09-25 16:28:37

标签: matplotlib backend

我需要创建一个可以在屏幕上show()编辑的图形对象(使用某些交互式后端时)或savefig()编辑,但我需要避免使用pylab / pyplot API,因为它设置默认后端并混淆其他事情。我将图形创建为

import matplotlib.figure
import matplotlib.backends.backend_qt4agg # or agg for headless backends
figure=matplotlig.figure.Figure()
canvas=matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg(figure)

但我仍然遗漏了一些东西。 documentation of Figure.show

If the figure was not created using figure(), it will lack a FigureManagerBase, and will raise an AttributeError.

我如何做呢?

1 个答案:

答案 0 :(得分:1)

您在交互式会话中获得的“标准”窗口是通过与figure_manager紧密相关的pyplot类系列运行的。

幸运的是,所有缩放/平移功能都包含在NavigationToolbar类系列中。

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar

def create_main_frame(self):
    # host widget
    self.main_frame = QtGui.QWidget()
    # set up the mpl side of things
    self.fig = Figure((24, 24), tight_layout=True)
    self.canvas = FigureCanvas(self.fig)
    # attach canvas to host widget
    self.canvas.setParent(self.main_frame)
    # make axes
    self.axes = self.fig.add_subplot(111, adjustable='datalim', aspect='equal')
    # make the tool bar
    self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

    # set up layout
    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(self.mpl_toolbar)
    vbox.addWidget(self.canvas)
    # set the layout to the host widget
    self.main_frame.setLayout(vbox)
    # make the host widget the central widget in the main frame of the class
    # this code is ripped from
    self.setCentralWidget(self.main_frame)