Sometimes a map alone is not sufficient for our data visualization needs. Often, we also want to explore datasets using classic statistical plots such as bar charts or histograms. This is were the following approach comes in handy: using the well-known matplotlib library and some Qt-based GUI elements, we can quickly create plots that help us better understand our data.

from qgis.PyQt.QtWidgets import QInputDialog, QMessageBox
from qgis.core import QgsVectorLayer
import matplotlib.pyplot as plt
# Step 1: Get the active layer
layer = iface.activeLayer()
if not layer or not isinstance(layer, QgsVectorLayer):
QMessageBox.critical(None, "Error", "Please select a valid vector layer.")
else:
# Step 2: Ask user for column name
fields = [field.name() for field in layer.fields()]
field_name, ok = QInputDialog.getItem(None, "Select Field", "Choose a numeric field for histogram:", fields, editable=False)
if ok and field_name:
# Step 3: Collect values from the selected column
values = []
for feature in layer.getFeatures():
attr = feature[field_name]
if isinstance(attr, (int, float)):
values.append(attr)
if not values:
QMessageBox.warning(None, "No Data", f"No numeric data found in field '{field_name}'.")
else:
# Step 4: Plot the histogram
plt.figure(figsize=(8, 6))
plt.hist(values, bins=20, edgecolor='black')
plt.title(f"Histogram of '{field_name}'")
plt.xlabel(field_name)
plt.ylabel("Frequency")
plt.grid(True)
plt.tight_layout()
# Step 5: Show the plot in a popup
plt.show()
PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!