TransWikia.com

Generate legend and export as image using PyQGIS

Geographic Information Systems Asked by M.SEL on January 20, 2021

I have a vector layer like :

vLayer = QgsVectorLayer('Point?crs=epsg:4326', vLayerName , providerName)
symbol = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'red' , 'stroke-color':'red'})
symbol.setSize(3)
symbolColorProperty = QgsProperty.fromExpression(someExpression)
symbol.symbolLayer(0).setDataDefinedProperty(QgsSymbolLayer.PropertyStrokeColor,symbolColorProperty)
vLayer.renderer().setSymbol(symbol)

Note that vLayer symbols have different color by QgsProperty expression.
I can generate and export a plot from vLayer as:

...
options  = QgsMapSettings()
options.setLayers([ vLayer ])
...

render = QgsMapRendererParallelJob(options)

render.start()
render.waitForFinished()
img = render.renderedImage()
img.save(image_path, "png")

How can I generate a legend according to that vLayer which shows me counts, percentages and symbols with colors like below.

enter image description here

One Answer

i have managed to generate a legend by using QgsPrintLayout and QgsLayoutItemLegend objects

layout = QgsPrintLayout( QgsProject.instance() )
layout.initializeDefaults()
layout.pageCollection().pages()[0].setPageSize(QgsLayoutSize( width, height, QgsUnitTypes.LayoutInches))
manager = QgsProject.instance().layoutManager()
manager.addLayout(layout)

legend = QgsLayoutItemLegend(layout)
legend.setTitle("title")

layerTree = QgsLayerTree()
for layer in layers: # add layers that you want to see in legend
    layerTree.addLayer(layer)

legend.model().setRootGroup(layerTree)
layout.addLayoutItem(legend)

exporter = QgsLayoutExporter(layout)
exporter.exportToImage(path, QgsLayoutExporter.ImageExportSettings())

Correct answer by M.SEL on January 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP