I'm trying to apply a color ramp to a QgsGraduatedSymbolRenderer
in PyQGIS 3 (QGIS 3.8) using the following code:
Getting the QgsGradientColorRamp
:
myStyle = QgsStyle().defaultStyle()
defaultColorRampNames = myStyle.colorRampNames()
ramp = myStyle.colorRamp(defaultColorRampNames[-6]) #Spectral color ramp
Applying it to the QgsGraduatedSymbolRenderer
:
myRenderer = QgsGraduatedSymbolRenderer('', myRangeList) #A list of break values
myRenderer.setSourceColorRamp(ramp)
myVectorLayer.setRenderer(myRenderer)
myVectorLayer.triggerRepaint()
Unfortunately the layer still shows in its original colors without the color map being applied. Upon looking in properties, however, oddly enough the color map is applied partially. The color map selected is indeed the one chosen ('Spectral'), but this isn't applied to the values' symbols. If I then just click on the color ramp and reapply it, it works, but I'd like to achieve this all through PyQGIS. I looked at similar questions here and the QGIS3 Python API and couldn't find a solution.
Best Answer
Updated answer:
Below is a recipe to apply a graduated renderer based on values in an attribute field, specifying the number of classes and color ramp.
I will leave the original answer below:
I have been through the same experience before, and (I may be wrong) but as far as I am aware, it is not possible to programmatically set a default color ramp and have it automatically applied. As you discovered, doing
setSourceColorRamp()
just sets that color ramp in the symbology dialog- it doesn't apply it to the renderer range symbols.You have to create each range, instantiate
QgsSymbol()
objects, set colors to them and pass those in to aQgsRendererRange()
constructor, together with the range and legend values.It's a bit hacky, but I knocked out the script below which will create a graduated symbology with 10 classes (like your example above) in a basic spectral color ramp. Just change the layer name to match yours:
Below is the result of this script run on a sample dataset- IBRA Bioregions of Australia, obtaining the graduation values from the "SHAPE_Area" field.
Based on the comment by @Cushen below, you could obtain a range of color values from an existing styled layer with a graduated ramp of the required number of classes and read those colors into a list object with a simple list comprehension: