Thursday, 15 September 2016

symbology - Applying graduated renderer in PyQGIS?



Just trying to run the following code already given in the pyqgis cookbook to create graduated colors symbology (as in example with 2 classes)


I define the source info for the shapefile but when I run execute the code within my test-plugin, it just adds the layer without classifiying. Just adds as usual, all polylines appear same.


Any solution or working code/method?


link to code in cookbook http://www.qgis.org/pyqgis-cookbook/vector.html#graduated-symbol-renderer


from qgis.core import  (QgsVectorLayer, QgsMapLayerRegistry, QgsGraduatedSymbolRendererV2, QgsSymbolV2,QgsRendererRangeV2)


myVectorLayer = QgsVectorLayer('C:/my_test_shape_file.shp', 'test_shp_file', 'ogr')

myTargetField = 'target_field'
myRangeList = []
myOpacity = 1

# Make our first symbol and range...
myMin = 0.0
myMax = 50.0

myLabel = 'Group 1'
myColour = QtGui.QColor('#ffee00')
mySymbol1 = QgsSymbolV2.defaultSymbol(myVectorLayer.geometryType())
mySymbol1.setColor(myColour)
mySymbol1.setAlpha(myOpacity)
myRange1 = QgsRendererRangeV2(myMin, myMax, mySymbol1, myLabel)
myRangeList.append(myRange1)

#now make another symbol and range...
myMin = 50.1

myMax = 100
myLabel = 'Group 2'
myColour = QtGui.QColor('#00eeff')
mySymbol2 = QgsSymbolV2.defaultSymbol(myVectorLayer.geometryType())
mySymbol2.setColor(myColour)
mySymbol2.setAlpha(myOpacity)
myRange2 = QgsRendererRangeV2( myMin, myMax, mySymbol2, myLabel)
myRangeList.append(myRange2)

myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)

myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
myRenderer.setClassAttribute(myTargetField)
myVectorLayer.setRendererV2(myRenderer)
QgsMapLayerRegistry.instance().addMapLayer(myVectorLayer)



@Kelly's code works perfectly.


However I noticed that both the code (one I have typed in my first message and yours in the 2nd message) DO NOT work in QGIS v1.7.3 but WORKS in QGIS v1.8.0. I think this was a bug(?) that already resolved in v1.8.0


And one more question;


Do you have any sample code for (natural breaks, Jenks) classification of the "numeric_attribute_field" based on given number of classes (i.e. no of classes will be a variable in the code, say "n", and I will pass that from the plugin GUI i.e. n = spinBox.value() )





No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...