I am working on my first pyqtgraph
plot which will be added to a Pyqt GUI. When the button addBtn
is pressed, a new data point should be added to the pyqtgraph
plot.
Problem: Adding the new x and y data as np.array
objects using the setData
function returns the error:
TypeError: setData(self, int, QVariant): argument 1 has unexpected type 'numpy.ndarray'
How can we fix the problem?
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import pyqtgraph as pg
import time
import numpy as np
class Screen(QMainWindow):
def __init__(self):
super(Screen, self).__init__()
self.initUI()
def initUI(self):
self.x = np.array([1,2,3,4])
self.y = np.array([1,4,9,16])
self.plt = pg.PlotWidget()
self.plt.plot(self.x, self.y)
addBtn = QPushButton('Add Datapoint')
addBtn.clicked.connect(self.addDataToPlot)
addBtn.show()
mainLayout = QVBoxLayout()
mainLayout.addWidget(addBtn)
mainLayout.addWidget(self.plt)
self.mainFrame = QWidget()
self.mainFrame.setLayout(mainLayout)
self.setCentralWidget(self.mainFrame)
def addDataToPlot(self):
data = {
'x': 5,
'y': 25
}
np.append(self.x, data['x'])
np.append(self.y, data['y'])
self.plt.setData(self.x, self.y)
app = QApplication(sys.argv)
window = Screen()
window.show()
sys.exit(app.exec_())
You must update the data in the plot not in the widget, for this we save it as an attribute.
def initUI(self):
self.x = np.array([1,2,3,4])
self.y = np.array([1,4,9,16])
self.plt = pg.PlotWidget()
self.plot = self.plt.plot(self.x, self.y)
[...]
Also in your case is not being updated, the function append returns an object that concatenates the input data, so you must save it
def addDataToPlot(self):
[...]
self.x = np.append(self.x, data['x'])
self.y =np.append(self.y, data['y'])
self.plot.setData(self.x, self.y)