使用python(x,y)中的mplwidget在同一图上绘制多条线

时间:2014-01-23 06:03:43

标签: python matplotlib widget qt-designer

我试图使用Qtdesigner插件中的mplwidget绘制多个线/点。通常当我在python中默认使用matplotlib时,它将保留第一个线图并在其上绘制另一个图形以进行比较。但是在Qtdesigner中,在我使用matplotlib作为小部件对象后,我选择了图形对象然后添加了子图,然后绘制图形,看起来它将删除旧的线图并绘制新的线图。我很确定编码有问题,但我是这个GUI的新手,我不确定哪个部分出错了

import sys
from PyQt4 import QtGui, QtCore
from window import Ui_MainWindow
import sqlite3
import os
from datetime import datetime
import calendar
import numpy


os.chdir("C:\Data")
conn = sqlite3.connect('FBG.db')
c=conn.cursor()

class Main(QtGui.QMainWindow):


    def searching_database(self):
        self.ui.listWidget.clear()
        data = self.ui.Inputname.text()
        for df in c.execute("select name from sqlite_master where type='table'; "):
            strdf=str(df)
            if len(data)==0:
                break
            if strdf[3:(len(data)+3)] == data: # the name for df start from position 3 due to "[u "
            self.ui.listWidget.addItem(strdf[3:-3])
            else:
                pass

    def delete_selection(self):
        self.ui.listWidget_3.takeItem(self.ui.listWidget_3.currentRow())


    def clear_graph(self):
        self.ui.listWidget_3.clear()
        self.ax.clear()
        self.ui.mplwidget.draw()

    def plot_graph(self):
        b=self.ui.listWidget.currentItem().text()
        b=str(b)
        self.ui.listWidget_3.addItem(b)

        time1= QtCore.QDateTime(self.ui.dateTimeEdit.dateTime())
        date1 = time1.toPyDateTime()
        timestamp1 = calendar.timegm(date1.utctimetuple()) #return a integer value

        time2= QtCore.QDateTime(self.ui.dateTimeEdit_2.dateTime())
        date2 = time2.toPyDateTime()
        timestamp2 = calendar.timegm(date2.utctimetuple()) 
        time=[]
        data=[]
        for df in c.execute('''select * from '''+ b ):
            time= numpy.append(time, df[0])
            data= numpy.append(data, df[1])
        self.ax.plot([2,4,5,6],[1,5,6,7],label=b) % set up for matplot widget
        self.ax.plot([1,3,4,5],[2,4,5,6],label=b+"afasdasdasd") % set up for matplot widget
        self.ax.legend() % set up for matplot widget
        self.ui.mplwidget.draw() % set up for matplot widget
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.Inputname.textChanged.connect(self.searching_database)
        self.ui.listWidget.itemDoubleClicked.connect(self.plot_graph)
        self.ui.pushButton.clicked.connect(self.plot_graph)
        self.ui.Delete.clicked.connect(self.delete_selection)
        self.ui.Clear.clicked.connect(self.clear_graph)
        self.ui.mplwidget.axes.set_title("Strain/Temperature vs Time") % set up for matplot widget
        self.fig = self.ui.mplwidget.figure % set up for matplot widget
        self.ax = self.fig.add_subplot(1,1,1) % set up for matplot widget
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window= Main()
    window.show()
    sys.exit(app.exec_())

代码运行正常。但我认为必须有一些代码阻止我得到我想要实现的目标。我认为这些代码可能会跟随“为matplot小部件设置%”。任何建议都会很好。

2 个答案:

答案 0 :(得分:0)

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import sys
import matplotlib.pyplot as plt

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class myWidget(QWidget):

    def __init__(self, parent=None):
        super(myWidget, self).__init__(parent)
        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.canvas)
        self.setLayout(self.vbox)

        self.plotCurve(self.canvas)


    def plotCurve(self, FigureCanvas):
        left, width = 0.1, 0.8
        rect1 = [left, 0.2, width, 0.6]

        FigureCanvas.figure.set_facecolor('white')
        axescolor  = '#f6f6f6'  # the axies background color
        FigureCanvas.figure.clear()
        ax1 = FigureCanvas.figure.add_axes(rect1, axisbg=axescolor)  #left, bottom, width, height

        ax1.set_title('Some Curve')

        x = range(10, 20)
        y = range(10, 20)
        z = range(20, 30)

        p1, = ax1.plot(x, y, 'ro')
        p2, = ax1.plot(x, z, '-')

        ax1.set_ylabel('Some Label')

        FigureCanvas.draw()

def main():
    app = QApplication(sys.argv)
    form = myWidget()
    form.show()
    app.exec_()


main()

答案 1 :(得分:0)

试试这个:

self.ui.mplwidget.axes.hold(True)

这可以让您在同一轴上绘制两个数据集,就像在交互模式下一样。为我工作!