You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多个Geopandas绘图图层添加多个图例?

解决Geopandas双图层图例不共存的问题

当使用Geopandas绘制面图层(基于vsu字段采用EqualInterval分级)和点图层(基于gk字段)时,即使两个图层都设置了legend=True,最终绘图结果仅显示一个图例。以下是原始代码及效果截图:

原始代码

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()

原始效果截图

绘图效果截图

修改方案

问题根源是Geopandas默认会用新图层的图例覆盖旧图例,需手动控制图例的位置与添加逻辑。以下是修改后的代码,可同时显示两个图层的图例:

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()

# 绘制面图层,指定图例位置并保存图例对象
face_plot = gdf.plot(column="vsu", scheme="EqualInterval", legend=True, ax=ax,
                     legend_kwds={'loc': 'upper right', 'bbox_to_anchor': (1.2, 1)})
face_legend = face_plot.get_legend()
fig.add_artist(face_legend)

# 绘制点图层,指定另一位置的图例并保存
point_plot = gdf_2.plot(column="gk", ax=ax, legend=True,
                        legend_kwds={'loc': 'lower right', 'bbox_to_anchor': (1.2, 0)})
point_legend = point_plot.get_legend()
fig.add_artist(point_legend)

# 调整布局,避免图例被画布截断
plt.subplots_adjust(right=0.8)

plt.show()

说明

  1. 通过legend_kwds的loc和bbox_to_anchor参数,为两个图例设置不重叠的位置(右上和右下);
  2. 分别获取两个图层的图例对象,通过fig.add_artist()将它们添加到画布中,防止被后续绘图操作覆盖;
  3. 使用plt.subplots_adjust()调整右侧边距,确保图例完整显示。

内容的提问来源于stack exchange,提问作者Norbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 18:37:40