In Styling vector layers, we covered how to style a point layer with a QgsSingleSymbolRenderer. This page covers other rendering options for point layers.

For more examples, have a look at the official PyQGIS Cookbook on vector layer styling.

Heatmap

The basic code for loading a point layer and styling it with a QgsHeatmapRenderer is:

uri = "E:/Geodata/NaturalEarth/vector_v4/natural_earth_vector.gpkg_v4.1.0/packages/natural_earth_vector.gpkg|layername=ne_110m_populated_places_simple"
vlayer = iface.addVectorLayer(uri, "places", "ogr")

heatmap = QgsHeatmapRenderer()
vlayer.setRenderer(heatmap)
vlayer.triggerRepaint()

Of course, the heatmap can be further customized, for example to increase the heatmap radius:

heatmap.setRadius(20)
vlayer.setRenderer(heatmap)
vlayer.triggerRepaint()

To change the color, we need to supply a different color ramp. To get a list of available color ramp names, use:

QgsStyle().defaultStyle().colorRampNames()

On my system, this returns:

['Blues', 'BrBG', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Inferno', 'Magma', 'OrRd', 'Oranges',
 'PRGn', 'PiYG', 'Plasma', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu',
 'RdYlGn', 'Reds', 'Spectral', 'Viridis', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'elections']

To apply one of these color ramps to the heatmap, use:

ramp = QgsStyle().defaultStyle().colorRamp('Blues')
heatmap.setColorRamp(ramp)
vlayer.setRenderer(heatmap)
vlayer.triggerRepaint()

Data-defined symbol size

Data-defined overrides for symbol layer properties can be created from expressions. An expression is the text we would have entered into the expression builder GUI (or would have created using the data-defined override assistant).

uri = "E:/Geodata/NaturalEarth/vector_v4/natural_earth_vector.gpkg_v4.1.0/packages/natural_earth_vector.gpkg|layername=ne_110m_populated_places_simple"
vlayer = iface.addVectorLayer(uri, "places", "ogr") 

exp = 'scale_linear("pop_max", 0, 10000000, 0, 7)'

renderer = vlayer.renderer().clone()
renderer.symbol().symbolLayer(0).setDataDefinedProperty(
    QgsSymbolLayer.PropertySize, QgsProperty.fromExpression(exp) )

vlayer.setRenderer(renderer) # necessary to emit rendererChanged signal (updates Layer Styling panel)
vlayer.triggerRepaint()

PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!

2 comments
  1. marcotagliabue said:

    Hi Anita, I think you can explain the variables and functions of “Data-defined symbol size” chapter to improve this page.
    Thanks for your work!

    • Hi Marco, I’ve simplified the expression to be less confusing. For explanations of QGIS expression functions, please refer to the official documentation.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.