matplotlib 如何在同一子图中绘制多个geopandas Dataframe 时添加图例?

daupos2t  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(144)

我有一个geopandas dataframe world,我使用以下命令创建:

import geopandas as gpd

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

我为usachina创建了两个不同的geodataframe,如下所示:

usa = world[world.name == "United States of America"]

china = world[world.name == "China"]

我想在Map上把美国标为蓝色,把中国标为红色。我使用以下代码行绘制了它:

fig, ax = plt.subplots(figsize = (20, 8))
world.plot(ax = ax, color = "whitesmoke", ec = "black")
usa.plot(ax = ax, color = "blue", label = "USA")
china.plot(ax = ax, color = "red", label = "China")
ax.legend()
plt.show()

如下所示:

我想添加图例,说明蓝色代表美国,红色代表中国。因此,我给出了上面代码中所示的标签。但是,我得到以下警告:
未找到具有可放入图例的标签的艺术家。请注意,在不带参数地调用legend()时,标签以下划线开头的艺术家将被忽略。
我无法添加图例。如何在此图中添加美国和中国的图例?可以使用geopandas和matplotlib吗?

z4iuyo4d

z4iuyo4d1#

我从来没有使用过geopandas,但是看结果似乎是那些填充的区域是PathCollection,这是不支持的传说。但我们可以创造传奇艺术家:

import geopandas as gpd
from matplotlib.lines import Line2D

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
usa = world[world.name == "United States of America"]
china = world[world.name == "China"]

fig, ax = plt.subplots()
world.plot(ax = ax, color = "whitesmoke", ec = "black")
usa.plot(ax = ax, color = "blue", label = "USA")
china.plot(ax = ax, color = "red", label = "China")

lines = [
    Line2D([0], [0], linestyle="none", marker="s", markersize=10, markerfacecolor=t.get_facecolor())
    for t in ax.collections[1:]
]
labels = [t.get_label() for t in ax.collections[1:]]
ax.legend(lines, labels)
plt.show()

相关问题