How to add histogram diagram and set its position, color etc. by PyQGIS (3.x)?

Viewed 132

I am trying to add histogram diagram by PyQGIS (3.x). Here is the sample point shapefile and the final output I am trying to achieve: the sample point shapefile and the final output I have tried the code below but my QGIS freezes. The current code does not include setting position of each histogram. I want to set histogram position based on field x and y.

Here are the settings I've done on QGIS manually to obtain the final output image: settings

Thank you in advance for your help and ideas!

layer=iface.activeLayer()
hist = QgsHistogramDiagram()
ds = QgsDiagramSettings()

# Set histogram and diagram settings:
dColors = {'export': QColor("#b7484b"),'import': QColor("#99dbfe")}
ds.categoryColors = dColors.values()
ds.categoryAttributes = dColors.keys()
ds.font = QFont("Helvetica", 12)
ds.transparency = 0
ds.size = QSizeF(50.0, 50.0)
ds.sizeType = 0
ds.labelPlacementMethod = 1
ds.scaleByArea = True
ds.minimumSize = 0
ds.BackgroundColor = QColor(255, 255, 255, 255)
ds.PenColor = QColor("black")
ds.penWidth = 0

# Set renderer:
renderer = QgsLinearlyInterpolatedDiagramRenderer()
renderer.setUpperValue(10)  # Here you should set the maximum value of both attributes
renderer.setUpperSize(QSizeF(20, 20))
renderer.setLowerValue(0)
renderer.setLowerSize(QSizeF(0, 0))
renderer.setDiagram(hist)
renderer.setDiagramSettings(ds)

# Set diagram layer settings:
layer.setDiagramRenderer(renderer)
dls = QgsDiagramLayerSettings()
dls.dist = 0
dls.priority = 0
dls.xPosColumn = -1
dls.yPosColumn = -1
dls.placement = 0

layer.setDiagramLayerSettings(dls)
layer.triggerRepaint()

0 Answers
Related