Skip to content
Advertisement

How to restrict a geopandas plot by coordinates?

I created a simple geopandas map using a shape file from OpenStreetMap (link).

import geopandas as gpd

map_gdf = gpd.read_file('path_to_shapefile')
map_gdf.plot()

Out:

Map of Berlin

How can I restrict the plot to only a certain portion of the image, essentially zooming in on a certain location. Can I do this by specifying the extent of the portion of the map which I’d like to plot in latitude and longitude?

Advertisement

Answer

The .plot() method of geopandas.GeoDataFrame returns a Matplotlib Axes object. In other words, you can simply assign the returned map to an Axes object and then use set_xlim and set_ylim to control the bound values.

For example, let’s use a sample dataset from geopandas

import geopandas as gpd
import matplotlib.pyplot as plt

# read sample dataset
data = gpd.datasets.get_path('naturalearth_lowres')
gdf = gpd.read_file(data)

# create an Axes object and plot the map
fig, ax = plt.subplots(figsize=(10, 10))
gdf.plot(ax=ax)

The default map returned looks like the following:

enter image description here

You can use set_xlim and set_ylim to change the bounds.

# create an Axes object and plot the map
fig, ax = plt.subplots(figsize=(10, 10))
gdf.plot(ax=ax)

ax.set_xlim(0, 100)
ax.set_ylim(-50, 50)

This will produce the following map

enter image description here


If you want to dynamically change the bounds, each geometry object in GeoDataFrame has a total_bounds attribute. Assuming you want to concentrate on Australia,

# create an Axes object and plot the map
fig, ax = plt.subplots(figsize=(10, 10))
gdf.plot(ax=ax)

xmin, ymin, xmax, ymax = gdf[gdf.name == 'Australia'].total_bounds
pad = 5  # add a padding around the geometry
ax.set_xlim(xmin-pad, xmax+pad)
ax.set_ylim(ymin-pad, ymax+pad)

This will get you

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement