2

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

1 Answer 1

1

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

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.