Getting PySide to work with matplotlib

前端 未结 3 622
暖寄归人
暖寄归人 2020-12-05 01:19

I have tried running the example code on the SciPy website, but I get this error:

Traceback (most recent call last):
  File \".\\matplotlibPySide.py\", line          


        
3条回答
  •  没有蜡笔的小新
    2020-12-05 01:44

    I had similar goals (LGPL, potential commercial use) and here's how I ended up getting it to work.

    Create a matplotlib widget (see here for a more detailed one for PyQt):

    import matplotlib
    
    matplotlib.use('Qt4Agg')
    matplotlib.rcParams['backend.qt4']='PySide'
    
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    
    class MatplotlibWidget(FigureCanvas):
    
        def __init__(self, parent=None,xlabel='x',ylabel='y',title='Title'):
            super(MatplotlibWidget, self).__init__(Figure())
    
            self.setParent(parent)
            self.figure = Figure()
            self.canvas = FigureCanvas(self.figure)
            self.axes = self.figure.add_subplot(111)
    
            self.axes.set_xlabel(xlabel)
            self.axes.set_ylabel(ylabel)
            self.axes.set_title(title)
    

    In Qt Designer I created a blank widget to hold my plot and then when I __init__ the main window I call setupPlot:

    def  setupPlot(self):
        # create a matplotlib widget
        self.DataPlot = MatplotlibWidget()
        # create a layout inside the blank widget and add the matplotlib widget        
        layout = QtGui.QVBoxLayout(self.ui.widget_PlotArea)        
        layout.addWidget(self.DataPlot,1)
    

    Then I call plotDataPoints as needed:

    def plotDataPoints(self,x,y):        
        self.DataPlot.axes.clear()
        self.DataPlot.axes.plot(x,y,'bo-')
        self.DataPlot.draw()
    

    Note: this clears and redraws the entire plot every time (since the shape of my data keeps changing) and so isn't fast.

提交回复
热议问题