Remove white spaces in subplots matplolib

48 Views Asked by At

I try to plot the subplots as shown below. It works okay but it still have some white spaces at the end of figure. Is it possible remove white spaces. Any help would be very great.

Here is the code and simulated data.

import numpy as np 
import xarray as xr 
import geopandas as gpd 
import requests

import matplotlib.pyplot as plt 
# Define a function to convert string coordinates into float 
def data_extract(link):
    text = requests.get(link).text.split(",")
    return np.array([float(i) for i in text if i])
# Get longitude and latitude
y = data_extract("https://raw.githubusercontent.com/tuyenhavan/test/main/latitude.txt")
x = data_extract("https://raw.githubusercontent.com/tuyenhavan/test/main/longtitude.txt")
# Make some random data covering the area with above coordinates
random_data = np.random.randint(0, 3, (22, 937, 399))
# Wrap them into Xarray DataArray
data = xr.DataArray(random_data, dims=("band", "y", "x"), coords={
    "band": np.arange(len(random_data)),
    "y": y,
    "x": x
})
# Get the study area 
aoi = gpd.read_file("https://raw.githubusercontent.com/tuyenhavan/test/main/area.geojson")
# Visualize the result 
fig, axes = plt.subplots(nrows=3, ncols=8, figsize=(12,16), sharex=True, sharey=True)

fig.subplots_adjust(hspace=-0.55)

cmap="Spectral"
# fig.subplots_adjust(wspace=0.2, hspace=0.25)
for i, ax in enumerate(axes.flatten()):
    if i<len(data):
        tem = data[i]
        tem=tem.rio.write_crs(aoi.crs)
        plot = tem.plot(ax=ax, cmap=cmap, add_colorbar=False, vmin=1, vmax=3)
        aoi.plot(ax=ax, color="None", edgecolor="black", linewidth=0.5)
        ax.set_title(f"{1+i}")
        ax.set_ylabel("")
        ax.set_xlabel("")
        ax.set_ylabel("")
        ax.set_xlabel("")

    else:
        ax.axis("off")

enter image description here

0

There are 0 best solutions below