2

So I'm a newbie, so sorry if this is an idiot question.

I'm trying to write a plugin for QGIS3 for my organisation, and I'd like to output a standalone figure (i.e. not in the QGIS window) as the final output. This way I can show rasters, line plots and vectors, in multiple subplots in a single figure and the user can save the figure directly if they want to.

I'm using Matplotlib as that's already available in pyQGIS, so I want to stick with that for logistic reasons.

My problem is that I have some nice QgsRasterLayer rasters (and QgsVectorLayer vectors too) that I'd like to display as some of the subplots but I don't know how to convert them into a form suitable display in Matplotlib. I can display them into the main QGIS window but that's not what I'm after. I need to plot them with Matplotlib.

Can anyone give me some suggestions? It's probably really obvious, but I'm just not finding the solution as my python experience is limited.

  • Is it possible for you to use gdal or rasterio? I found some answers here: gis.stackexchange.com/questions/32995/…. This exports the data to a numpy array, which matplotlib understands. – Andreas Müller Apr 3 at 8:57
  • Thanks - yes GDAL is possible, but I need the rasters in a QgsRasterLayer and display them in the main QGIS interface. That part is all ok. But if I took a GDAL approach I assume I'd have to open them a second time, which seems inelegant. Or have I got that wrong? I suspect the answer lies somewhere in QgsRasterLayer.dataProvider.block but so far it's still escaping me. – SJJ Apr 3 at 13:03
1

Barry Rowlingson build an plugin for QGIS2 called "Rasterlang" (https://www.maths.lancs.ac.uk/~rowlings/Software/Qgis/Plugins/rasterlang/), inside there is a modul named layers.py with a function called layerAsArray():

def layerAsArray(layer):
    """ read the data from a single-band layer into a numpy/Numeric array.
    Only works for gdal layers!
    """

    gd = gdal.Open(str(layer.source()))
    array = gd.ReadAsArray()
    return array

Like you I was concerned about loading data twice, but didn't see a way through QgsRasterLayer. Provider seems to be always gdal, but you can't "cast" it back and use ReadAsArray() on the provider.

  • Ok thanks - am re-assured that others have struggled with the same problem. It's not just me then. As some of my rasters are large I am concerned about the time and memory implications of loading twice. But if its the only route, then it's the one I will take although I remain open to other suggestions. Thank you for your kind help. Sarj – SJJ Apr 3 at 15:32

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.