[GIS] How to apply categorized symbols to polygon layer with PyQGIS

pyqgisqgissymbology

I'm fetching a polygon layer from postgres using the following:

uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "mydb", "postgres", "xxx")
uri.setDataSource("public", "my_table", "geom")
lyr = QgsVectorLayer(uri.uri(), "Blocks", "postgres")
QgsMapLayerRegistry.instance().addMapLayer(lyr)

This layer has an attribute field named blocks that has 6 values:
'A-6', 'B-4', 'G-5', 'D-2', 'P-7', 'C-3'.

I want to apply the color green to polygons where the attribute 'block' value is 'B-4' and red color to the other polygons in the layer that have a different value in the 'block' attribute.

I've seen code to apply graduated symbols using PyQGIS but I want categorized symbols.

How can I do this?

Best Answer

Categorized symbols and graduated symbols are applied in pretty much the same way. The only difference is that graduated symbols are taking into account certain ranges, whereas, categorized is simply taking in the actual field value. Quite honestly, you could literally replicate the code given from the PyQGis cookbook site: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#id19 and instead of inserting "upper" and "lower" ranges values, just put the 6 values you have: 'A-6', 'B-4', 'G-5', 'D-2', 'P-7', 'C-3'. It works the exact same way.

# create graduated marker symbol
blocks = (('Label_Name1', 'A-6', 'A-6', 'red'), \
            ('Label_Name2', 'B-4', 'B-4', 'green'), \
            ('Label_Name3', 'G-5', 'G-5' 'red'), \
            ('Label_Name4', 'D-2', 'D-2', 'red'), \
            ('Label_name5', 'P-7', 'P-7', 'red'), \
            ('Label_Name6', 'C-3', 'C-3', 'red'))

ranges = []
for label, lower, upper, color in blocks:
    rng = QgsRendererRangeV2(lower, upper, label)
    ranges.append(rng)
field = "blocks"
renderer = QgsGraduatedSymbolRendererV2(field, ranges)
layer.setRendererV2(renderer)  
Related Question