Search code examples
pythonnumpymatplotlibgdal

multitple matplotlib-axes from gdal-rasters


I am a little stuck in plotting multiple rasters in one figure with matplotlib. I have a list with the 6 paths to the rasters and I would make a figure with 3x2 subplots. I'm not really sure which of the matplotlib-approaches works best for this. Moreover I have the problem, that I don't know how to make one single colorbar/legend for all plots.

my somewhat messy code looks like this at the moment but doesn't feel really good...

fig, axs = plt.subplots(3, 2, figsize=(18, 10))
i = 0
j = 0

fig.suptitle("Multiple Images")

for c, img in enumerate(imgs):
    name = img.split(os.sep)[1]
    gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
    img_array = gdalobj.GetRasterBand(2).ReadAsArray()
    if c < 2:
        axs[0,c].imshow(img_array, cmap="gray")
        axs[0,c].set_title(name)
    elif 2 <= c < 4:
        axs[1,i].imshow(img_array, cmap="gray")
        axs[1,i].set_title(name)
        i+=1
    else:
        axs[2,j].imshow(img_array, cmap="gray")
        axs[2,j].set_title(name)
        j+=1

I really don't think that this is the best way, but it somehow works. However, I would like to generate one single colorbar and I don't know how to do it...


Solution

  • You can reduce your messy code to the following by iterating over the flattened array of axis objects. As for the color bar, you can refer to the existing posts, for example this one

    for ax, img in zip(axs.flatten(), imgs):
        name = img.split(os.sep)[1]
        gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
        img_array = gdalobj.GetRasterBand(2).ReadAsArray()
        ax.imshow(img_array, cmap="gray")
        ax.set_title(name)