2

I'm unsure how to automate the process for PyQGIS to update the pie charts to a fixed size of 12. The approach I used is not working out and no pie charts are being created.

enter image description here

lyr = iface.activeLayer()

diagram = QgsPieDiagram()

ds = QgsDiagramSettings()

dColors = {'Field1': QColor('#5a09a6'),'Field2': QColor('#ff9200')}

ds.categoryColors = dColors.values()
ds.categoryAttributes = dColors.keys()
ds.sizeType = 0
ds.categoryLabels = ds.categoryAttributes

dr = QgsLinearlyInterpolatedDiagramRenderer()
#dr.setClassificationField('SAMPLE NUM')
dr.setDiagram(diagram)
dr.setDiagramSettings(ds)

lyr.setDiagramRenderer(dr)
dls = QgsDiagramLayerSettings()

lyr.setDiagramLayerSettings(dls)
lyr.triggerRepaint()

1 Answer 1

3

I spent a lot of time trying to find the method to check 'Fixed size' or/and uncheck 'Scaled size' options and it was not possible. However, I found out a totally equivalent approach by using following code. The key was in to use a high number (1000000) in 'setLowerValue' method of QgsLinearlyInterpolatedDiagramRenderer class to avoid 'Scaled size' in the field used as base of classification.

lyr = iface.activeLayer()

diagram = QgsPieDiagram()

ds = QgsDiagramSettings()

dColors = {'Field1': QColor('#5a09a6'),'Field2': QColor('#ff9200')}

ds.categoryColors = dColors.values()
ds.categoryAttributes = dColors.keys()
ds.categoryLabels = ds.categoryAttributes
ds.sizeType = 0 #0 = Millimeters, 1 = Map Units, 2 = Pixels, 4 = Points, 5 = Inches

# Set renderer:
dr = QgsLinearlyInterpolatedDiagramRenderer()
dr.setLowerValue(1000000)
dr.setUpperSize(QSizeF(12, 12))
dr.setClassificationField('field1')
dr.setDiagram(diagram)
dr.setDiagramSettings(ds)

lyr.setDiagramRenderer(dr)
dls = QgsDiagramLayerSettings()

lyr.setDiagramLayerSettings(dls)
lyr.triggerRepaint()

I ran above code with following vector layer; where it can be observed in its attributes table 'field1' and 'field2' fields with different arbitrary values.

enter image description here

Result with Pie Diagram was as follows (Observe that Size scale was placed in 12):

enter image description here

I also applied manually 'Fixed size' option and result remained unchanged; as it can be observed in following image. I ran the script again and result was identical. It worked.

enter image description here

2
  • Thanks this really answered my question. I never would have gotten this answer by myself. Commented Jan 29, 2021 at 13:09
  • You're welcome. So, you could mark as accepted this answer. Thanks in advance.
    – xunilk
    Commented Jan 29, 2021 at 16:52

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.