Data Visualization In PyQt: A Guide To Plotting Data Curves using Pyqtgraph

Posted by


Pyqtgraph is a powerful library for creating interactive 2D and 3D visualizations in Python. In this tutorial, we will learn how to plot data curves in Pyqtgraph and create stunning data visualizations in PyQt.

Step 1: Install Pyqtgraph

Before we start plotting data curves in Pyqtgraph, make sure you have Pyqtgraph installed. You can install Pyqtgraph using the following command:

pip install pyqtgraph

Step 2: Import the necessary modules

In order to plot data curves in Pyqtgraph, you need to import the necessary modules. Here is an example of how to import Pyqtgraph and PyQt modules:

import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication

Step 3: Create a simple PyQt application

Next, we need to create a simple PyQt application to display the data curves. Here is an example of how to create a PyQt application:

app = QApplication([])

Step 4: Create a Pyqtgraph plot widget

Now, we need to create a Pyqtgraph plot widget where we will plot our data curves. Here is an example of how to create a simple plot widget:

plot_widget = pg.PlotWidget()
plot_widget.show()

Step 5: Plot data curves on the plot widget

Now that we have created a plot widget, we can start plotting data curves on it. Here is an example of how to plot a simple data curve:

data = [1, 2, 3, 4, 5]
plot_widget.plot(data)

This will plot a simple line plot using the data provided in the list.

Step 6: Customize the plot

You can further customize the plot by changing the line color, line width, line style, etc. Here is an example of how to customize the plot:

plot_widget.plot(data, pen=(255, 0, 0), width=2, style=pg.QtCore.Qt.DashLine)

This will plot the data curve with a red color, a line width of 2, and a dashed line style.

Step 7: Add labels and legends to the plot

You can also add labels and legends to the plot to make it more informative. Here is an example of how to add labels and legends to the plot:

plot_widget.setLabel('left', 'Y-axis')
plot_widget.setLabel('bottom', 'X-axis')
plot_widget.addLegend()

This will add labels to the X and Y axes and a legend to the plot.

Step 8: Add multiple data curves to the plot

You can add multiple data curves to the plot by plotting them one after the other. Here is an example of how to add multiple data curves to the plot:

data1 = [1, 2, 3, 4, 5]
data2 = [5, 4, 3, 2, 1]

plot_widget.plot(data1, pen=(255, 0, 0), width=2, style=pg.QtCore.Qt.DashLine, name='Data1')
plot_widget.plot(data2, pen=(0, 255, 0), width=2, style=pg.QtCore.Qt.SolidLine, name='Data2')

This will plot two data curves with different colors, line styles, and legends on the plot widget.

Step 9: Run the PyQt application

Finally, you need to run the PyQt application to display the plot widget with the data curves. Here is an example of how to run the PyQt application:

app.exec_()

This will start the PyQt application and display the plot widget with the data curves.

That’s it! You have successfully plotted data curves in Pyqtgraph and created stunning data visualizations in PyQt. Feel free to explore more features of Pyqtgraph and create more complex data visualizations.

0 0 votes
Article Rating

Leave a Reply

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ParwizForogh
2 hours ago

You can support me on Patreon
https://www.patreon.com/parwizforogh

@soulonfiretv
2 hours ago

Kindly show how to ADD a secondary Y Axis in PyQt5 and pyqtgraph

@bennguyen1313
2 hours ago

Any suggestions how to plot live, real-time data using de-queue/pipes? I have a process that receives data from the serial port that I want to send to pyqtgraph for fast plotting!

For example, the github Haschtl/RealTimeOpenControl :

from collections import deque

from PyQt5 import QtWidgets, QtCore, QtGui

import stack

import pyqtgraph as pg

import random

class ExampleApp(QtWidgets.QMainWindow, stack.Ui_MainWindow):

def __init__(self):

super().__init__()

self.setupUi(self)

self.graphicsView.getAxis('left').setLabel('Data Value', color='#0000ff')

self.graphicsView.getAxis('bottom').setLabel('time', 's')

self.graphicsView.showGrid(x=True, y=True)

self.graphicsView.setYRange(0,10)

self.graphicsView.addLine(y=5,pen=pg.mkPen('y'))

self.graphicsView.addLine(y=7,pen=pg.mkPen('r'))

self.curve = self.graphicsView.plot()

self.L = deque([0], maxlen=10)

self.t = deque([0], maxlen=10)

self.timer = QtCore.QTimer(self)

self.timer.timeout.connect(self.updateplot)

self.timer.start(500)

self.timer = QtCore.QTimer()

self.timer.setInterval(50)

self.timer.timeout.connect(self.update_plot_data)

self.timer.start()

def update_plot_data(self):

self.x = self.x[1:] # Remove the first y element.

self.x.append(self.x[-1] + 1) # Add a new value 1 higher than the last.

self.y = self.y[1:] # Remove the first

self.y.append( randint(0,100)) # Add a new random value.

self.data_line.setData(self.x, self.y) # Update the data.

def updateplot(self):

val = round(random.uniform(0,10), 2)

self.L.append(val)

self.t.append(self.t[-1]+1)

self.curve.setData(self.t, self.L)

######################

######################

######################

######################

from PyQt5 import QtWidgets, QtCore

from pyqtgraph import PlotWidget, plot

import pyqtgraph as pg

import sys # We need sys so that we can pass argv to QApplication

import os

from random import randint

class MainWindow(QtWidgets.QMainWindow):

def __init__(self, *args, **kwargs):

super(MainWindow, self).__init__(*args, **kwargs)

self.graphWidget = pg.PlotWidget()

self.setCentralWidget(self.graphWidget)

self.x = list(range(100)) # 100 time points

self.y = [randint(0,100) for _ in range(100)] # 100 data points

self.graphWidget.setBackground('w')

pen = pg.mkPen(color=(255, 0, 0))

self.data_line = self.graphWidget.plot(self.x, self.y, pen=pen)

app = QtWidgets.QApplication(sys.argv)

w = MainWindow()

w.show()

sys.exit(app.exec_())

######################
######################

######################

######################

## –– coding: utf-8 –

import sys

from PyQt5 import QtCore, QtGui, QtWidgets

from pyqtgraph import PlotWidget

import pyqtgraph

import numpy as np

import serial

class MainWindow(QtWidgets.QMainWindow):

def __init__(self, parent=None):

super(MainWindow, self).__init__(parent)

self.plot_data = {

'ax':np.full(100, 0),

'ay':np.full(100, 0),

'az':np.full(100, 0),

'gx':np.full(100, 0),

'gy':np.full(100, 0),

'gz':np.full(100, 0),

'mx':np.full(100, 0),

'my':np.full(100, 0),

'mz':np.full(100, 0),

't' :np.arange(100)

}

self.plot_data_color = {

'ax':'#FF0000',

'ay':'#00FF00',

'az':'#0000FF',

'gx':'#DDDD00',

'gy':'#00DDDD',

'gz':'#DD00DD',

'mx':'#808020',

'my':'#208080',

'mz':'#802080'

}

self.resize(600, 600)

self.setStyleSheet("QMainWindow {background: 'white';}")

self.serial = serial.Serial('COM3', 115200, timeout=None)

# leyout

self.centralwidget = QtWidgets.QWidget(self)

self.setCentralWidget(self.centralwidget)

self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)

# pot widget

self.plotwidget = { axis:PlotWidget(self) for axis in ['a','g','m'] }

titles = { 'a':'Acceleration','g':'Gyro','m':'Geomagnetism' }

for key in self.plotwidget:

self.plotwidget[key].setBackground("#FFFFFFFF")

plotitem = self.plotwidget[key].plotItem

plotitem.setLabels(bottom='time', left=titles[key])

plotitem.getAxis('bottom').setPen( pyqtgraph.mkPen(color='#000000') )

plotitem.getAxis('left').setPen( pyqtgraph.mkPen(color='#000000') )

# leyout

self.verticalLayout.addWidget(self.plotwidget['a'])

self.verticalLayout.addWidget(self.plotwidget['g'])

self.verticalLayout.addWidget(self.plotwidget['m'])

# timer

self.timer = QtCore.QTimer()

self.timer.timeout.connect(self.update_data)

self.timer.start(50)

def update_data(self):

# stop timer

self.timer.stop()

# clear

self.plotwidget['a'].clear()

self.plotwidget['g'].clear()

self.plotwidget['m'].clear()

# get serial

try:

line = self.serial.readline().decode()

data = { data.split(':')[0]:data.split(':')[1] for data in line.split(',') }

# increase time

self.plot_data['t'] = np.append( self.plot_data['t'][1:], self.plot_data['t'][-1]+1 )

# add data

for key in self.plot_data:

if key == 't':

continue

self.plot_data[key] = np.append( self.plot_data[key][1:], float(data[key]) )

# set data

self.plotwidget[key[0]].addItem(

pyqtgraph.PlotDataItem(

x=self.plot_data['t'], y=self.plot_data[key],

pen=pyqtgraph.mkPen(color=self.plot_data_color[key], width=3), antialias=True

)

)

except:

pass

# start timer

self.timer.start(50)

def main():

app = QtWidgets.QApplication(sys.argv)

mainwindow = MainWindow(None)

mainwindow.show()

app.exec()

if _name_ == '__main__':

main()

@amityadav7239
2 hours ago

How to add these graphs in one of the frame in qtwindow application where one frame contain graph 1 and another contain graph 2

4
0
Would love your thoughts, please comment.x
()
x