[GIS] Use PyQGIS to import CSV and draw points using different color

pyqgispythonpython-2.7qgisqgis-2

A CSV file contains columns latitude, longitude and color.

uri = "file:///C:/data/balls.csv?type=csv&xField=longitude&yField=latitude&spatialIndex=no&subsetIndex=no&watchFile=no"
vlayer = QgsVectorLayer(uri, 'Balls', "delimitedtext")

Using the Python console in QGIS, how can we draw each row in the CSV as a point whose color depends on the value in the color column of the imported CSV?

It's my understanding that QgsDataSourceURI.setDataSource() can do such a WHERE query during the import, but only works on PostGIS.

Best Answer

To do that you should access to data defined properties for the symbol layer and set the color by passing the field name as expression. You can do it like:

uri = "file:///C:/data/balls.csv?type=csv&xField=longitude&yField=latitude&spatialIndex=no&subsetIndex=no&watchFile=no"
vlayer = QgsVectorLayer(uri, 'Balls', "delimitedtext")

mySymbol = QgsSymbolV2.defaultSymbol(vlayer.geometryType())
mySymbolLayer = mySymbol.symbolLayer(0)
## replace COLOR_FIELD with the column name of your CSV data
mySymbolLayer.setDataDefinedProperty("color", '"COLOR_FIELD"')
vlayer.rendererV2().symbols()[0].changeSymbolLayer(0, mySymbolLayer)

QgsMapLayerRegistry.instance().addMapLayer(vlayer)
Related Question