2

I have a plugin and I want to symbology a vector file with some default ramp colors but I see that in graduated symbology is not so easy as in graduated symbology.

Is it possible to assign a default ramp color to a vector file?

My code is very confusing because I tried so many examples but I couldn't get the result.

for code, (color, label) in attribute_sym.items():
    sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
    sym.setColor(QColor(color))
    category = QgsRendererCategoryV2(code, sym, label)
    categories.append(category)

self.field = self.dockwidget.comboBox.currentText()
renderer = QgsCategorizedSymbolRendererV2(self.field, categories)
layer.setRendererV2(renderer)           
QgsMapLayerRegistry.instance().addMapLayer(layer)

This code works but I don't want to allways define the list with the colors, because I am trying to symbology several fields. Is it some way of using the default ramp colors?

2

You may get access to the default ramp colors in this way:

defStyle = QgsStyleV2().defaultStyle()
defaultColorRampNames = defStyle.colorRampNames()
print defaultColorRampNames

# The print command returns this list:
# [u'Blues', u'BrBG', u'BuGn', u'BuPu', u'GnBu', u'Greens', u'Greys', u'Inferno', u'Magma', u'OrRd', u'Oranges', u'PRGn', u'PiYG', u'Plasma', u'PuBu', u'PuBuGn', u'PuOr', u'PuRd', u'Purples', u'RdBu', u'RdGy', u'RdPu', u'RdYlBu', u'RdYlGn', u'Reds', u'Spectral', u'Viridis', u'YlGn', u'YlGnBu', u'YlOrBr', u'YlOrRd']

Then, you may set the ramp by specifying the index of the ramp from the list printed in the previous code (for example, 0 is the index for the 'Blues' ramp):

ramp = defStyle.colorRamp(defaultColorRampNames[0]) # 0 is the index for the 'Blues' ramp

With these premises, you may slightly edit your code in this way:

defStyle = QgsStyleV2().defaultStyle()
defaultColorRampNames = defStyle.colorRampNames()
ramp = defStyle.colorRamp(defaultColorRampNames[0])

for code, (color, label) in attribute_sym.items():
    sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
    category = QgsRendererCategoryV2(code, sym, label)
    categories.append(category)

self.field = self.dockwidget.comboBox.currentText()
renderer = QgsCategorizedSymbolRendererV2(self.field, categories)
renderer.updateColorRamp(ramp) #update the color ramp before setting the renderer
layer.setRendererV2(renderer)
QgsMapLayerRegistry.instance().addMapLayer(layer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.