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()
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
