1

I am developing a hexabinning QGIS plugin. I have used the following script to perform hexabinning https://github.com/maphew/mhwcode/blob/1ef8338e20ff24ddbe741af225e556b9d81ec416/gis/qgis/h3-grid-from-layer.py

However, once the hexabinned layers are created, I have to manually perform the following steps on the layer to show the results.

Right click on the layer -> choose properties - > and set the value, symbol, and color ramp, and then click classify. Please refer to the image below.

In the plugin, it would be nice to automate the above tasks through code so that they are performed automatically when a user clicks the binning button, to prevent the user having to do all this.

I have written the following code, based on the answer here: Applying categorized symbol to each feature using PyQGIS It executes without errors, but the result layer (Hex 7) is empty. When I click on the layer (in the Layers panel) it does not show anything.

# Get the active layer (must be a vector layer)
layer = QgsProject.instance().mapLayersByName("Hex 7")[0] # qgis.utils.iface.activeLayer()
   
# get unique values 
fni = layer.dataProvider().fieldNameIndex('numpoints') 
#layer.fieldNameIndex(1)
print('count ' + str(fni))
unique_values = layer.dataProvider().uniqueValues(fni)

# define categories
categories = []
count = 0
for unique_value in unique_values:
count = count + 1

    # initialize the default symbol for this geometry type
    # symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    print('total count ' + str(count))   
    

    # configure a symbol layer
    layer_style = {}
    layer_style['color'] = '%d, %d, %d' % (randrange(0,256), randrange(0,256), randrange(0,256))
    layer_style['outline'] = '#000000'
    symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style)

    # replace default symbol layer with the configured one
    if symbol_layer is not None:
        symbol.changeSymbolLayer(0, symbol_layer)

        # create renderer object
        category = QgsRendererCategory(unique_value, symbol, str(unique_value))
        # entry for the list of category items
        categories.append(category)

    # create renderer object
    renderer = QgsCategorizedSymbolRenderer('test', categories)

    # assign the created renderer to the layer
    if renderer is not None:
        layer.setRenderer(renderer)

    layer.triggerRepaint()

enter image description here

Please see the 22 second YouTube video that shows the process I want to automate. https://www.youtube.com/watch?v=hNyMosEZx1o

Result:

Useful links:

Qgis python to apply polygon Symbology

Categorizing by attribute using custom QGIS plugin via python programming?

Automatic pyqgis categorized renderer classification

Applying categorized symbol to each feature using PyQGIS

Update rule-based symbology QGIS

Most helpful

Apply graduated symbology renderer works in Python console but not in standalone script

4
  • can explain why this is not a duplicate of gis.stackexchange.com/questions/175068/…
    – Ian Turton
    Mar 19 at 11:51
  • Thank you. That seems helpful. Shoud I feed "numpoints" instead of "test" in line 7 "fni = layer.fieldNameIndex('test')"?
    – sharmapn
    Mar 19 at 12:42
  • I will try to customise that. If that works, I will put the customised version as the answer to this question.
    – sharmapn
    Mar 19 at 12:43
  • @IanTurton I have edited the question with code and results.
    – sharmapn
    Mar 20 at 12:22

1 Answer 1

1

Try this:

layer = qgis.utils.iface.activeLayer()

color_ramp = QgsStyle().defaultStyle().colorRamp('Spectral')

renderer = QgsGraduatedSymbolRenderer.createRenderer(
    vlayer=layer,
    attrName=layer.fields().names()[-1],
    classes=5,
    mode=QgsGraduatedSymbolRenderer.Quantile,
    symbol=QgsSymbol.defaultSymbol(layer.geometryType()),
    ramp=color_ramp
)
layer.setRenderer(renderer)
layer.triggerRepaint()
1
  • Works awesome! Just had to specify layername like this instead: "layer = QgsProject.instance().mapLayersByName(layername)[0]"
    – sharmapn
    Mar 25 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.