Use matplotlib in pyqt to draw dynamic curves

Source: Internet
Author: User

I. project background:

After reading the matplotlib for python developers book, I basically learned how to display curves in pyqt, so I wrote one myself.

Ii. Requirement Description:

1) the X axis shows the time point. The length is 1 minute, and a point is drawn every second. If the length of the X axis exceeds 1 minute, the scale is shifted to 1 second to achieve dynamic effect.

2) the Y axis shows a random value, ranging from 1 to 100.

Iii. Preparations

1 environment: python3.3, eric5, pyqt4

4. Start:

Use Eric to create a new project:

 

At the early stage of design coding, Eric's two windows are mainly used: source code and form browser, similar to Delphi.

In the form browser, right-click, new form, and select main window as the form type, as shown below:

 

The name is mplmainwindow.

 

Put two Pushbutton on the interface, horizontally layout, and then put a widget to modify the name, horizontal and vertical policies.

The interface is designed as follows:

 

Finally, execute the grid layout.

To embed matplotlib into mplcanvas, You need to upgrade mplcanvas, right-click and execute promote, and enter the class name as mplcanvaswrapper. This class is used to compile matplotlib code. The file name is mplcanvaswrapper.

 

Click Add and then click upgrade.

 

Save the current design form.

This completes the interface design. The QT interface stores XML content and needs to be converted to Python code in two ways:

Method 1: Use the built-in functions of Eric: In the form browser, right-click the form UI file and execute the compile form command. The ui_mplmain1_1_py file is generated in the current UI file directory.

Method 2: run the command [original file name of pyuic 4-O destination file] in cmd, as follows:

 

A mplmainwindow. py file is generated in the project folder.

 

Use method 1 in this document. The default file name is ui_mplmain1_1_py.

Open this file and do two things:

1) In the last line, there will be the following sentence: "From mplcodewrapper import mplcodewrapper", which is exactly the same as the class name file name entered during the upgrade. Cut this sentence to the top of the file, yes.

2) Change the inheritance of the form from object to qtgui. qmainwindow.

 

Then we will create the file mplcodewrapper. py

In Eric's source code browser, create a new file, save it as mplcodewrapper. py, and write two blank codes:

From pyqt4 import qtcore

From pyqt4 import qtgui

From ui_mplmainwindow import ui_mainwindow

Class code_mainwindow (ui_mainwindow): # modify to inherit from ui_mainwindow

Def _ init _ (self, parent = none ):

Super (code_mainwindow, self). _ init _ (parent)

Pass

So far, the entire framework has been set up, and both the interface file and the drawing file have been set up.

 

Add event processing for the form below.

In line with the principle of separation of interface and code, we create a new py file for writing interface code

Create the file code_mplmain1_0000py in the current directory. It is mainly used to bind button events and intermediate logic.

I have mentioned a bunch of things above, but I may not quite understand why I want to change it. Here I will draw a class diagram as follows:

 

The file ui_mplmainwindow generated by pyqt is a pure interface file, similar to the designer file of C #. The code_mplmainwindow file is similar to the CS file of C #, and the drawing logic is placed in mplcanvaswrapper, in this way, the interface and implementation are separated.

How can I display and change the time on the X axis?

1) matplotlib provides the plot_date Method for displaying the time on the X axis.

2) Design a thread for generating data and drawing. Based on the single function principle, we need to divide the generated data and drawing into two types for implementation, one for data processing and one for drawing board. The improved class diagram is as follows:

 

Notes:

1) when the form is closed, a close confirmation prompt should be provided, which is implemented by rewriting closeevent.

2) The thread must have an exit signal.

The complete code is as follows:

1) ui_mplmain1_1_py

#-*-Coding: UTF-8 -*-

 

# Form implementation generated from reading UI file 'mplmainwindow. Ui'

#

# Created: Mon Aug 11 14:18:31 2014

# By: pyqt4 UI code generator 4.10.3

#

# Warning! All changes made in this file will be lost!

 

From pyqt4 import qtcore, qtgui

From mplcanvaswrapper import mplcanvaswrapper

 

Try:

_ Fromutf8 = qtcore. qstring. fromutf8

T attributeerror:

Def _ fromutf8 (s ):

Return s

 

Try:

_ Encoding = qtgui. qapplication. unicodeutf8

Def _ translate (context, text, disambig ):

Return qtgui. qapplication. Translate (context, text, disambig, _ encoding)

T attributeerror:

Def _ translate (context, text, disambig ):

Return qtgui. qapplication. Translate (context, text, disambig)

# Inheritent from qtgui. qmainwindow

Class ui_mainwindow (qtgui. qmainwindow ):

Def setupui (self, mainwindow ):

Mainwindow. setobjectname (_ fromutf8 ("mainwindow "))

Mainwindow. Resize (690,427)

Self. centralwidget = qtgui. qwidget (mainwindow)

Self. centralwidget. setobjectname (_ fromutf8 ("centralwidget "))

Self. gridlayout = qtgui. qgridlayout (self. centralwidget)

Self. gridlayout. setobjectname (_ fromutf8 ("gridlayout "))

Self. horizontallayout = qtgui. qhboxlayout ()

Self. horizontallayout. setobjectname (_ fromutf8 ("horizontallayout "))

Self. btnstart = qtgui. qpushbutton (self. centralwidget)

Self. btnstart. setobjectname (_ fromutf8 ("btnstart "))

Self. horizontallayout. addwidget (self. btnstart)

Self. btnpause = qtgui. qpushbutton (self. centralwidget)

Self. btnpause. setobjectname (_ fromutf8 ("btnpause "))

Self. horizontallayout. addwidget (self. btnpause)

Spaceritem = qtgui. qspaceritem (40, 20, qtgui. qsizepolicy. Expanding, qtgui. qsizepolicy. Minimum)

Self. horizontallayout. additem (spaceritem)

Self. gridlayout. addlayout (self. horizontallayout, 0, 0, 1, 1)

Self. mplcanvas = mplcanvaswrapper (self. centralwidget)

Sizepolicy = qtgui. qsizepolicy (qtgui. qsizepolicy. Expanding, qtgui. qsizepolicy. Expanding)

Sizepolicy. sethorizontalstretch (0)

Sizepolicy. setverticalstretch (0)

Sizepolicy. setheightforwidth (self. mplcanvas. sizepolicy (). hasheightforwidth ())

Self. mplcanvas. setsizepolicy (sizepolicy)

Self. mplcanvas. setobjectname (_ fromutf8 ("mplcanvas "))

Self. gridlayout. addwidget (self. mplcanvas, 1, 0, 1, 1)

Mainwindow. setcentralwidget (self. centralwidget)

 

Self. retranslateui (mainwindow)

Qtcore. qmetaobject. connectslotsbyname (mainwindow)

 

Def retranslateui (self, mainwindow ):

Mainwindow. setwindowtitle (_ translate ("mainwindow", "mainwindow", none ))

Self. btnstart. settext (_ translate ("mainwindow", "Start", none ))

Self. btnpause. settext (_ translate ("mainwindow", "Suspend", none ))

2) code_mplmain1_1_py

From pyqt4 import qtgui, qtcore

From ui_mplmainwindow import ui_mainwindow

Class code_mainwindow (ui_mainwindow ):

Def _ init _ (self, parent = none ):

Super (code_mainwindow, self). _ init _ (parent)

Self. setupui (Self)

Self. btnstart. clicked. Connect (self. startplot)

Self. btnpause. clicked. Connect (self. pauseplot)

Def startplot (Self ):

'''Beginto plot '''

Self. mplcanvas. startplot ()

Pass

Def pauseplot (Self ):

'''Pause plot '''

Self. mplcanvas. pauseplot ()

Pass

Def releaseplot (Self ):

'''Stop and release thread '''

Self. mplcanvas. releaseplot ()

 

Def closeevent (self, event ):

Result = qtgui. qmessagebox. Question (self,

"Confirm exit ...",

"Are you sure you want to exit? ",

Qtgui. qmessagebox. Yes | qtgui. qmessagebox. No)

Event. Ignore ()

 

If result = qtgui. qmessagebox. Yes:

Self. releaseplot () # release thread's resouce

Event. Accept ()

 

If _ name _ = "_ main __":

Import sys

APP = qtgui. qapplication (SYS. argv)

Ui = code_mainwindow ()

Ui. Show ()

Sys.exit(app.exe C _())

 

3) mplcanvaswrapper. py

From pyqt4 import qtgui

From matplotlib. backends. backend_qt4agg import figurecanvasqtagg as figurecanvas

From matplotlib. backends. backend_qt4agg import navigationtoolbar2qtagg as navigationtoolbar

From matplotlib. Figure import figure

Import numpy as NP

From array import Array

Import time

Import random

Import threading

From datetime import datetime

From matplotlib. Dates import date2num, minutelocator, secondlocator, dateformatter

 

X_minutes = 1

Y_max = 100.

Y_min = 1

Interval = 1

Maxcounter = int (x_minutes * 60/interval)

Class mplcanvas (figurecanvas ):

Def _ init _ (Self ):

Self. Fig = figure ()

Self. Ax = self. Fig. add_subplot (111)

Figurecanvas. _ init _ (self, self. Fig)

Figurecanvas. setsizepolicy (self, qtgui. qsizepolicy. Expanding, qtgui. qsizepolicy. Expanding)

Figurecanvas. updategeometry (Self)

Self. Ax. set_xlabel ("time of data generator ")

Self. Ax. set_ylabel ('random data value ')

Self. Ax. Legend ()

Self. Ax. set_ylim (y_min, y_max)

Self. Ax. xaxis. set_major_locator (minutelocator () # Every minute is a major Locator

Self. Ax. xaxis. set_minor_locator (secondlocator ([10, 20, 30, 40]) # Every 10 second is a minor Locator

Self. Ax. xaxis. set_major_formatter (dateformatter ('% H: % m: % s') # Tick label formatter

Self. curveobj = none # draw object

Def plot (self, datax, datay ):

If self. curveobj is none:

# Create draw object once

Self. curveobj, = self. Ax. plot_date (NP. Array (datax), NP. Array (datay), 'bo -')

Else:

# Update data of draw object

Self. curveobj. set_data (NP. Array (datax), NP. Array (datay ))

# Update limit of X axis, to make sure it can move

Self. Ax. set_xlim (datax [0], datax [-1])

Ticklabels = self. Ax. xaxis. get_ticklabels ()

For tick in ticklabels:

Tick. set_rotation (25)

Self. Draw ()

Class mplcanvaswrapper (qtgui. qwidget ):

Def _ init _ (self, parent = none ):

Qtgui. qwidget. _ init _ (self, parent)

Self. Canvas = mplcanvas ()

Self. VBL = qtgui. qvboxlayout ()

Self. NTB = navigationtoolbar (self. Canvas, parent)

Self. VBL. addwidget (self. NTB)

Self. VBL. addwidget (self. Canvas)

Self. setlayout (self. VBL)

Self. datax = []

Self. datay = []

Self. initdatagenerator ()

Def startplot (Self ):

Self. _ generating = true

Def pauseplot (Self ):

Self. _ generating = false

Pass

Def initdatagenerator (Self ):

Self. _ generating = false

Self. _ exit = false

Self. tdata = threading. Thread (name = "datagenerator", target = self. generatedata)

Self. tdata. Start ()

Def releaseplot (Self ):

Self. _ exit = true

Self. tdata. Join ()

Def generatedata (Self ):

Counter = 0

While (true ):

If self. _ Exit:

Break

If self. _ generating:

Newdata = random. randint (y_min, y_max)

Newtime = date2num (datetime. Now ())

Self. datax. append (newtime)

Self. datay. append (newdata)

Self. Canvas. Plot (self. datax, self. datay)

If counter> = maxcounter:

Self. datax. Pop (0)

Self. datay. Pop (0)

Else:

Counter + = 1

Time. Sleep (interval)

 

:

 

Summary:

Through this program, I am familiar with the following points:

1) Eric and qtdesigner are used, and the interface and logic are separated.

2) rewrite a form event

3) bind signals and slots

4) use threads

5) Use of object-oriented matplotlib

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.