I'm new on QGIS and PyQGIS. I'm trying to create a plugin which aims to apply a style on a vector layer (generated from a csv file) and then save the map as a png file.

The style I apply on the vector layer is a heatmap style. The problem is that I don't have a legend for the heatmap.. . At least I would like to have the colors and the percentage of the different levels.

Do you have any idea of how I could do that? Or is it even possible?

I'm not using the heatmap plugin, only applying a heatmap style from a .qml file.

I searched a lot and I couldn't find anything helpful about that... any help would be great.


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

or by directly typing the color ramp's name:

ramp = defStyle.colorRamp('Blues')

With these premises, you may use this sample code:

layer = iface.activeLayer() # load the layer as you want

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

renderer = QgsHeatmapRenderer()
renderer.setRadius(5) # change the radius value as you want
renderer.setMaximumValue(0) # set 0 for automatically calculating it
ramp = defStyle.colorRamp('Blues')
renderer.setWeightExpression('my_field') # set the field name here

for creating a Heatmap renderer (of blues):

enter image description here

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.