TransWikia.com

Overlapping legend: How to put geopandas legend next to the map?

Geographic Information Systems Asked on February 11, 2021

I am using geopandas and contextily to plot building data (polygon) from OpenStreetMap. The problem is, the legend is overlapping the map. Is there any way to put the legend next to the map? or plot the map without legend, but export the legend separately from the map?

I hope the image helps.

here’s my code to produce the map (I know the code is a little different, but it yields the same map):

from matplotlib import pyplot as plt
import geopandas as gpd
import contextily as ctx
%matplotlib inline

buildings = gpd.read_file("buildings.shp")
fig, ax = plt.subplots(1,1,figsize=(9,9))
buildings.to_crs(epsg=3857).plot(column='building', ax=ax, cmap="Paired", legend=True)
ctx.add_basemap(ax, url=ctx.providers.Esri.WorldTopoMap)
ax.axis('off')
plt.show()

The problem

One Answer

You can specify legend_kwds and bbox_to_anchor positioning within that. You may want to fiddle with the actual values.

buildings = gpd.read_file("buildings.shp")
fig, ax = plt.subplots(1,1,figsize=(9,9))
buildings.to_crs(epsg=3857).plot(column='building', ax=ax, cmap="Paired", legend=True, legend_kwds={'bbox_to_anchor': (1.3, 1)})
ctx.add_basemap(ax, url=ctx.providers.Esri.WorldTopoMap)
ax.axis('off')
plt.show()

Answered by martinfleis on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP