Tuesday, 17 September 2019

Using QGIS GUI predefined colorramps in Python console / PyQGIS?


When using the QGIS Gui, there are plenty of predefined colorramps to choose from when styling a layer with e.g. categorized symbology.


QGIS predefined colorramps


When using the Python console for PyQGIS scripting, this page of the API docs describes how to create your own colorramp that you can then apply to a renderer object, for example:


# create a new colorramp
colorRamp = QgsVectorGradientColorRampV2.create({'color1' : '0,255,0,255',
'color2' : '255,0,0,255',
'stops' : '0.5;255,255,0,255'})


# set up an empty categorized renderer and assign the colorramp
renderer = QgsCategorizedSymbolRendererV2(field, [])
renderer.setSourceColorRamp(colorRamp)

Is there a way to access the predefined colorramps that are accessible from the GUI and assign them to a renderer instead of creating my own?



Answer



In general you should look at this page of the APIs documentation. As a working example see as follows:


vl = iface.activeLayer()
## get default style
myStyle = QgsStyleV2().defaultStyle()

## get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....]
defaultColorRampNames = myStyle.colorRampNames()
## setting ramp to Blues, first index of defaultColorRampNames
ramp = myStyle.colorRamp(defaultColorRampNames[0])
# set up an empty categorized renderer and assign the color ramp
renderer = QgsCategorizedSymbolRendererV2(field, [])
renderer.setSourceColorRamp(ramp)
vl.setRendererV2(renderer)

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...