Search code examples
pythonmatplotlibpyqtgraph

Color is not working in pyqtgraph like the way it works in matplotlib


I have a 2d numpy array as following

import numpy as np
agents = np.array([[  1. , -71.8,  41.2],
       [  1. , -71.8,  41.3],
       [  0. , -71.8,  41.4],
       [  0. , -71.7,  41.4],
       [  0. , -71.6,  41.4]])

Now I want to visualize it. In matplotlib i can do something like this as I need different color based on the value of the first column.

import matplotlib.pyplot as plt
plt.scatter(agents [:,1],agents [:,2],c=agents [:,0])

But how can I get the same result in pyqtgraph? I tried this

app = QtGui.QApplication(sys.argv)
mw = QtGui.QMainWindow()
mw.resize(800, 800)
view = pg.GraphicsLayoutWidget()
mw.setCentralWidget(view)
mw.setWindowTitle('pyqtgraph example: ScatterPlot')
w1 = view.addPlot()
x = agents[:,1]
y = agents[:,2]
z = agents[:,0]
s = pg.ScatterPlotItem(x, y,pen=pg.mkPen(z))
w1.addItem(s)
mw.show()
sys.exit(QtGui.QApplication.exec_())

Got this exception

Exception: Not sure how to make a color from "(array([1., 0., 0., 0.]),)"

Solution

  • If you want to set a color for each point you must pass a list of the colors, in your case you are passing it a list, instead you must pass it QPen if you want to set the colors of the border or QBrush if you want to set the fill color.

    From what I understand you you want the latest:

    s = pg.ScatterPlotItem(x, y, brush=[pg.mkBrush(v) for v in z])
    # or 
    # s = pg.ScatterPlotItem(x, y, brush=list(map(pg.mkBrush, z)))
    

    If you want to set the border color then use:

    s = pg.ScatterPlotItem(x, y, pen=[pg.mkPen(v) for v in z])
    # or 
    # s = pg.ScatterPlotItem(x, y, pen=list(map(pg.mkPen, z)))