将Matplotlib图嵌入到PyQt中

时间:2015-10-20 09:13:21

标签: python matplotlib pyqt embed

过去几天我一直试图将matplotlib嵌入到PyQt中,但在你说什么之前,我已经到过每个网站都可以帮助我。

当我运行代码时,它生成一个1乘1的图形,但实际上并没有绘制任何图形

from __future__ import unicode_literals
import sys
import os
import random
from matplotlib.backends import qt4_compat
use_pyside = qt4_compat.QT_API == qt4_compat.QT_API_PYSIDE
if use_pyside:
    from PySide import QtGui, QtCore
else:
    from PyQt4 import QtGui, QtCore

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
import scipy.io
import os
import pandas as pd

progname = os.path.basename(sys.argv[0])
progversion = "0.1"


class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()

        #
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    def extract_data(self, name):

        #setting up lists

        Stim_trig = []
        Stim_order = []
        Sch_wav = []

        data = scipy.io.loadmat(name)

        for k,v in data.items():

            #Sends Sch_wav data to a list
            if "Sch_wav" in k:

                for d in (((v[0])[0])[4]):
                    Sch_wav.append(d[0])

            #Sends StimTrig to a list
            if k=="StimTrig":
                for g in (((v[0])[0])[4]):
                    Stim_trig.append(g[0])
                Stim_trig.append(Stim_trig[-1]+1)

            #Sends Stim order to a list

                for w in (((v[0])[0])[5]):
                    Stim_order.append(w[0])

        superdata = []

        #Prepares grouping stimuli and trigger

        for i in range(len(Stim_trig)-1):
            fire = []
            for p in Sch_wav:
                if p > Stim_trig[i] and p < Stim_trig[i+1]:
                    fire.append(p - Stim_trig[i])
            superdata.append([Stim_order[i],fire])


        #sorts all the data
        superdata.sort()

        alladdedup = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[62]]
        count = 0
        for d in superdata:
            if d[0] == (alladdedup[count])[0]:
                for j in d[1]:
                    ((alladdedup)[count]).append(j)
            else:
                count += 1
        #places time stamps of triggers in lists for each trigger

        for l in alladdedup:
            l.pop(0)
            l.sort()
            #removes title and sorts data

        ffmsb = []

        #finds number of firings for each milisecond bin
        for v in alladdedup:
            fmsb = []

            for b in range(100):
                msbc = b/100
                msb = []

                for t in v:
                    if t > msbc and t < msbc + 0.01:
                        msb.append(t)

                fmsb.append(len(msb))

            ffmsb.append(fmsb)
        #returns list of stimuli firings per milisecond bin
        return ffmsb
    #End of Sorting Code
    #Start of Graphing Code
    def stimuli_graph(self):

        #Set file to use and the stimuli wanted. In this case stimuli 1 is being used
        filename = ("654508_rec02_all.mat"[1])
        self.extract_data(filename)

        #Creates parameters for index
        numberlist = []
        for i in range(100):
            numberlist.append(i/100)

        #Adjusts the y-axis max according to the y-axis of a graphed stimuli e.g. If plotted graph has y-axis of 10
        # then it'll be adjusted by 1.3. So it'll change to 13
        x = 0
        for i in filename:
            if i > x:
                x = i*1.3

        #Dataframes the data from extract_data
        c = pd.Series(filename, index = numberlist)
        neurons = pd.DataFrame((c))

        #This is where the data gets graphed. I know this is where the problem occurs, I just don't know where
        #This code is a mess and for that I am sorry
        times = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
        ax = neurons.plot(
            kind = 'bar',
            title = 'Number of neurons firing for stimuli '+str(1),
            legend = False,
            xlim = (0, 100),
            ylim = (0, x),
            width = 1,
            position = 0,
            edgecolor = 'white',
            xticks = (np.arange(min(times), max(times), 10)) #Makes the x-axis label in increments of 0.1 instead of 0.01
        )
        ax.set_xlabel('Time (s)')
        ax.set_ylabel('Neurons Firing')

        t = arange(0, 100, 1)
        self.axes.plot(t, neurons)

class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.file_menu = QtGui.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
                                 QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)

        self.help_menu = QtGui.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)

        self.main_widget = QtGui.QWidget(self)

        l = QtGui.QVBoxLayout(self.main_widget)
        sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(sc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.statusBar().showMessage("All hail matplotlib!", 2000)

    def fileQuit(self):
        self.close()

    def closeEvent(self, ce):
        self.fileQuit()


qApp = QtGui.QApplication(sys.argv)

aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
#qApp.exec_()

图表中使用的数据是从外部文件中提取的

0 个答案:

没有答案