Search code examples
pythonmatplotliblegendgeopandas

How can I plot multiple legends for multiple geopandas plot layers?


I want two show both legends for both of my plot layers but it shows only just one legend. How can I fix this?

import geopandas
from shapely.geometry import Point
from shapely.geometry import Polygon
import matplotlib.pyplot as plt

coords_1 = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.))
coords_2 = ((1., 1.), (2., 1.), (2., 2.), (1., 2.), (1., 1.))

d = {'vsu': [10, 15], 'geometry': [Polygon(coords_1), Polygon(coords_2)]}
gdf = geopandas.GeoDataFrame(d)

p = {'gk': ["a", "b"], 'geometry': [Point(0.5, 0.5), Point(1.5, 1.5)]}
gdf_2 = geopandas.GeoDataFrame(p)

fig, ax = plt.subplots()

gdf.plot(column="vsu", scheme="EqualInterval", legend=True, ax=ax)
gdf_2.plot(column = "gk", ax=ax, legend=True)

plt.show()

enter image description here


Solution

  • The first legend needs to be saved and then later added again to the plot.

    fig, ax = plt.subplots()
    
    gdf.plot(column="vsu", scheme="EqualInterval", legend=True, ax=ax)
    leg1 = ax.get_legend()
    
    gdf_2.plot(column = "gk", ax=ax, legend=True)
    
    ax.add_artist(leg1)
    
    plt.show()