Automatically export a series of feature-based graphics with QGIS and Python (without Data Plotly)

In our previous articles, we looked at how to create graphs in QGIS with Data Plotly. Today, we’re going one step further: automate the generation of a graph by range (or any other entity), exporting the results as PNG images, ready to insert into a report.

And good news: no need to code a plugin, we’re going to use the QGIS Python console, with pandas and plotly.



Objective

Automatically create :

  • One graph per range, showing the amount of waste by type
  • One PNG image file per graph
  • Without repeated clicks or manual manipulation


Example used

We have a layer of beach waste records, with the following fields:

  1. beach: beach name
  2. waste_type: type (plastic, metal…)
  3. quantity: number of objects detected


The Python script in QGIS

Here is a script that you can copy into the QGIS Python console:

import os
import pandas as pd
import plotly.express as px

# Dossier de sortie
output_folder = "C:/temp/export_graphiques"
os.makedirs(output_folder, exist_ok=True)

# Couche active
layer = iface.activeLayer()

# Extraction des données
data = []
for f in layer.getFeatures():
    data.append({
        "plage": f["plage"],
        "type_dechet": f["type_dechet"],
        "quantite": f["quantite"]
    })

# Convertir en DataFrame
df = pd.DataFrame(data)

# Générer un graphique par plage
for plage, group in df.groupby("plage"):
    fig = px.bar(
        group,
        x="type_dechet",
        y="quantite",
        title=f"Déchets par type – {plage}",
        labels={"quantite": "Quantité", "type_dechet": "Type de déchet"},
        color="type_dechet"
    )
    fig.update_layout(showlegend=False)
    fig.write_image(os.path.join(output_folder, f"graph_{plage}.png"))

print("✅ Graphiques exportés dans :", output_folder)


Prerequisites

For the script to work, check that :

  • Your QGIS Python environment contains pandas , plotly and kaleido
  • If not, you can install it via the command prompt:

    • C:\OSGeo4W\OSGeo4W.bat > python3 -m pip install pandas plotly kaleido


Customize

You can modify :

  • The grouping field (“range”) to plot by commune, date, etc.
  • Chart type: use px.pie, px.line, px.histogram…


Expected results

In your file, you’ll obtain :

graph_Anse_Mourouk.png
graph_Pointe_Coton.png
graph_Graviers.png
...

Each image corresponds to a range, with a clear graphic ready for insertion in a report or atlas.

If you modify the code to produce pie charts:

import plotly.express as px
import os

for plage, group in df.groupby("plage"):
fig = px.pie(
group,
names="type_dechet", # valeurs catégorielles
values="quantite", # valeurs quantitatives
title=f"Répartition des déchets – {plage}",
color="type_dechet"
)
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.write_image(os.path.join(output_folder, f"graph_{plage}.png"))


You get:

To sum up

Although Data Plotly is handy for creating graphs in QGIS, it is not scriptable in Python. However, by extracting data and using plotly, you benefit from :

  • total control,
  • a reusable script,
  • professional visuals.


Coming soon…

In a future article, we’ll look at how to automatically integrate these graphics into a QGIS Atlas, to create fully customized PDF reports.


Si cet article vous a intéressé et que vous pensez qu'il pourrait bénéficier à d'autres personnes, n'hésitez pas à le partager sur vos réseaux sociaux en utilisant les boutons ci-dessous. Votre partage est apprécié !

Leave a Reply

Your email address will not be published. Required fields are marked *