0

I'm trying to add a contextily basemap to a Matplotlib figure containing a GeoPandas data frame. When I just plot the data frame using df.plot the map extent is calculated correctly.

However, when I try adding a contextily basemap the map extent (and zoom level) is calculated wrongly and the following warning is shown:

UserWarning: The inferred zoom level of 27 is not valid for the current tile provider (valid zooms: 0 - 20).

I'm trying to execute the following code:

df = gpd.read_file('linz/StatBez_Linz_EPSG_4326.gml')
df = df.to_crs(epsg=3857)

fig = plt.figure(figsize=(16,9))
ax = plt.subplot()
ctx.add_basemap(ax = ax, source=ctx.providers.Stamen.Toner, crs=df.crs.to_string())
df.plot(color='none',edgecolor='green', ax = ax)

The output of df.tail() can be seen here:

enter image description here

The gml file is from data.gv.at

4
  • are you sure your code is correct? the second line should not work because you haven't defined linz_districts. Despite, what does the first df's crs (try identifying the crs of the first df before doing the projection)? Have you manually adjust the contextily zoom parameter to 20? – sutan Nov 9 '20 at 19:16
  • Thanks for pointing that out, @sutan, I edited the code above. I changed all the variable names before copying the code into the question. The values that come out of the crs projection are as expected. Except for the code above, nothing was set up in contextily, therefore also the zoom level wasn't manually set – tuesday Nov 9 '20 at 22:21
  • 1
    First plot GeoDataFrame, then add a basemap. – martinfleis Nov 9 '20 at 22:37
  • That solves it, thanks a lot! – tuesday Nov 10 '20 at 8:43
0

As pointed out in a comment above, the GeoDataFrame needs to be plotted on the axis first before adding the basemap with contextily.

df = gpd.read_file('linz/StatBez_Linz_EPSG_4326.gml')
df = df.to_crs(epsg=3857)

fig = plt.figure(figsize=(16,9))
ax = plt.subplot()
df.plot(color='none',edgecolor='green', ax = ax)
ctx.add_basemap(ax = ax, source=ctx.providers.Stamen.Toner)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.