import numpy as np
from PyQt5 import QtWidgets
import pyqtgraph as pg
import pyqtgraph.exporters
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph import GraphicsLayoutWidget
class PyQtGraphExportTest(GraphicsLayoutWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Test pyqtgraph export')
self.resize(640, 400)
# Set up a couple of stacked plots
self.plot1 = self.addPlot(row=0, col=0)
self.trace1 = self.plot1.plot(np.random.random(10))
self.plot1.enableAutoRange(pg.ViewBox.XYAxes)
self.plot2 = self.addPlot(row=1, col=0)
self.trace2 = self.plot2.plot(np.random.random(10))
self.plot2.enableAutoRange(pg.ViewBox.XYAxes)
# Store reference to exporter so it doesn't have to be initialised every
# time it's called. Note though the window needs to be displayed so
# mapping from plot to device coordinates is set up, that hasn't
# happened yet as this GraphicsLayoutWidget is also the Qt app window,
# so we'll create it later on.
self.exporter = None
# Configure a timer to act as trigger event for export. This could be a
# data acquisition event, button press etc.
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update_data)
self.timer.start(2000)
def update_data(self):
# Create the exporter if needed, now window is displayed on screen
if not self.exporter:
# Here we are passing the exporter the GraphicsLayout object that is
# the central item (ci) inside this GraphicsLayoutWidget. That in
# turn contains the two PlotItem objects.
self.exporter = pg.exporters.ImageExporter(self.ci) self.exporter.parameters()['width'] = 640
# Get some new data, update plot and export
self.trace1.setData(np.random.random(10))
self.trace2.setData(np.random.random(10))
self.exporter.export('exported_image.png')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = PyQtGraphExportTest()
window.show()
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
sys.exit(app.exec_())