PyQtGraph - Adding Item to Plot Window

PyQtGraph - Adding Item to Plot Window

Adding an item to a plot window in PyQtGraph, a Python library used for scientific graphics and GUIs, is quite straightforward. PyQtGraph is known for its performance on graphical plots, and it's widely used in scientific applications. Here's a step-by-step guide on how to add an item, such as a line or a scatter plot, to a PyQtGraph plot window:

Step 1: Install PyQtGraph

If you haven't installed PyQtGraph, you can do so using pip:

pip install pyqtgraph 

Step 2: Basic Setup

Start by setting up a basic PyQt application with a plot window:

import sys import pyqtgraph as pg from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication(sys.argv) mainWindow = QMainWindow() centralWidget = pg.GraphicsLayoutWidget() mainWindow.setCentralWidget(centralWidget) mainWindow.show() 

Step 3: Create a Plot

Add a plot to your window:

plotItem = centralWidget.addPlot(title="My Plot") 

Step 4: Add an Item to the Plot

You can add different types of items to your plot. Here are examples of adding a line and a scatter plot:

  • Adding a Line:

    import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) line = pg.PlotDataItem(x, y, pen='r') plotItem.addItem(line) 
  • Adding a Scatter Plot:

    scatter = pg.ScatterPlotItem(pen=pg.mkPen(None), brush=pg.mkBrush(255, 100, 100, 200), size=10) scatter.setData(x, y) plotItem.addItem(scatter) 

Step 5: Run the Application

Finally, run your PyQt application:

sys.exit(app.exec_()) 

Complete Example

Putting it all together, here's a complete script to create a PyQtGraph window with a line and scatter plot:

import sys import numpy as np import pyqtgraph as pg from PyQt5.QtWidgets import QApplication, QMainWindow # Initialize the application app = QApplication(sys.argv) # Create main window and central widget mainWindow = QMainWindow() centralWidget = pg.GraphicsLayoutWidget() mainWindow.setCentralWidget(centralWidget) mainWindow.show() # Add a plot to the central widget plotItem = centralWidget.addPlot(title="My Plot") # Create and add a line plot x = np.linspace(0, 10, 100) y = np.sin(x) line = pg.PlotDataItem(x, y, pen='r') plotItem.addItem(line) # Create and add a scatter plot scatter = pg.ScatterPlotItem(pen=pg.mkPen(None), brush=pg.mkBrush(255, 100, 100, 200), size=10) scatter.setData(x, y) plotItem.addItem(scatter) # Execute the application sys.exit(app.exec_()) 

In this example, you create a PyQtGraph window with a plot that includes both a line and scatter plot. You can easily adjust this to plot different types of data, or add additional plot elements as needed for your application.


More Tags

jquery-select2-4 compilation string-parsing bundler out optimization dispatchevent keyboard android-espresso memory-leak-detector

More Programming Guides

Other Guides

More Programming Examples