79198363

Date: 2024-11-17 23:40:48
Score: 0.5
Natty:
Report link

You need to save the legend from the first plot using ax.get_legend, then manually add it back in using ax.add_artist. Here's a minimal example:

import geopandas as gpd
import matplotlib.pyplot as plt

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# subset to just a few countries in North America
gdf = gdf.loc[gdf.name.isin(['Canada', 'United States of America', 'Mexico'])]

gdf2 = gpd.GeoDataFrame(gdf.drop(columns='geometry'), geometry=gdf.centroid)

fig, ax = plt.subplots()
gdf.plot(column='name', ax=ax, legend=True)
leg1 = ax.get_legend() # save the legend from the first plot
gdf2.plot(column='continent', ax=ax, legend=True, legend_kwds={'loc': 'upper left'}, cmap='Pastel1')
ax.add_artist(leg1) # add the first legend back in

this produces the following (nonsensical) figure: enter image description here

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: sdg