Search code examples
pythongeopandascontextily

Getting contextily basemap to fill plots


I'm trying to create a 2x2 subplot using the following:

import geopandas as gpd
import matplotlib.pyplot as plt
import contextily as ctx

site = gdf.groupby('Site_name')

plt.figure(figsize =(20,20))

# Iterate through sites

for i, (Site_name, site_gdf) in enumerate(site):
    # create subplot axes in a 2x2 grid
    ax = plt.subplot(2, 2, i + 1) # nrows, ncols, axes position
    # plot the site on these axes
    site_gdf.plot(ax=ax)
    ctx.add_basemap(ax, source=ctx.providers.Esri.WorldImagery)
    # set the title
    ax.set_title(Site_name)
    # set the aspect
    # adjustable datalim ensure that the plots have the same axes size
    ax.set_aspect('equal', adjustable='datalim')

plt.tight_layout()
plt.show()

The problem occurs that the extent of the basemaps within the subplots are restricted to the overlaid point data. How do I change it so that each subplot has a basemap that covers the whole subplot.

Plot output


Solution

  • my solution was, that i searched for my outermost points and then changed my matplotlib axes with

    ax.set_xlim(x_min-addition, x_max+addition)
    ax.set_ylim(y_min-addition, y_max+addition)
    

    addition in this case is just a number to increase the view on the points, like 0.001. x_min was the smallest point, x_max the biggest, and so on... Afterwards, i got my basemap.

    ctx.add_basemap(ax,...)
    

    If you know your outermost boundaries for all points, you could pass them directly. The result should be in the same size. If you don't know your boundaries, you need to find them first. Therefore you could iterate over your points and just compare them (just an example):

    for point_data_x, point_data_y in site_data:
        if point_data_x < x_min:
            x_min = point_data_x
        elif point_data_x > x_max:
            x_max = point_data_x
        if point_data_y < y_min:
            y_min = point_data_y
        elif point_data_y > y_max:
            y_max = point_data_y
    

    Kind regards