Search code examples
pythonmatplotlibgeopandas

How to delete margin between figure and subplot in matplotlib


fig, ax = plt.subplots(figsize=(10, 6))
fig.patch.set_facecolor('#87ceeb')
ax.set_axis_off()

ax.set_xlim(minx, maxx)
ax.set_ylim(miny, maxy)

gdf.plot(ax=ax, facecolor='#dcdcdd', edgecolor='#a5abae')
plt.show()

With this code i build this visualization:

enter image description here

I tried many options like

plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

And

ax.set_position([0, 0, 1, 1])

etc. But all of them don't work

How can I delete a small margin between figure and visualization made by gdf.plot() ?


Solution

  • You have a bunch of options. The simple/quickest one is to turn off the clip-on :

    gdf.plot(ax=ax, facecolor="#dcdcdd", edgecolor="#a5abae", clip_on=False)
    

    Or using an overlayed box :

    fig, ax = plt.subplots(figsize=(10, 6))
    ax.set(xlim=(minx, maxx), ylim=(miny, maxy))
    ax.set_axis_off()
    
    from shapely import box
    gpd.GeoSeries([box(*tb)]).plot(ax=ax, fc="#87ceeb")
    gdf.plot(ax=ax, facecolor="#dcdcdd", edgecolor="#a5abae")
    

    Or with ax.patch instead of fig.patch :

    fig, ax = plt.subplots(figsize=(10, 6))
    
    ax.patch.set_facecolor("#87ceeb")
    ax.set(xticks=[], yticks=[], xlim=(minx, maxx), ylim=(miny, maxy))
    ax.spines[list(ax.spines)].set_visible(False)
    
    gdf.plot(ax=ax, facecolor="#dcdcdd", edgecolor="#a5abae")
    

    enter image description here

    Used input :

    import geopandas as gpd
    
    url = "https://naciscdn.org/naturalearth/110m/cultural/110m_cultural.zip"
    
    gdf = gpd.read_file(url, layer="ne_110m_admin_0_countries")
    gdf.to_crs(gdf.estimate_utm_crs(), inplace=True)
    
    tb = gdf.query("ADMIN == 'Ukraine'").total_bounds
    minx, miny, maxx, maxy = tb