Search code examples
matplotlibgeopandas

geopandas and matplotlib - plotting multiple polygons without changing plot extent


I am importing two geojson files and plotting them. When I add the second file which are state boundaries, the plot zooms to that layer's extent. I'd like plot the 2nd file (usaStates) on top of the first without changing the plot extent.

myPolygon = geopandas.read_file("/pathToFile/myPolygon.geojson")
ax = myPolygon.plot(figsize=(5, 5), alpha=0.5, edgecolor='k',facecolor='none')
usaStates = geopandas.read_file("/pathToFile/states.geojson")
usaStates.plot(ax=ax, edgecolor='k',facecolor='none')

The plot ends up looking like below when I want it to be zoomed into a more regional view equal to the bounds from the first file.

enter image description here


Solution

  • You can force the extent of the plot with the first geojson coordinates :

    xmin, ymin, xmax, ymax = myPolygon.total_bounds
    
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)