繁体   English   中英

如何在使用 Python 中的 matplotlib 在同一子图中绘制多个 geopandas 数据帧时添加图例?

[英]How can I add legend while plotting multiple geopandas dataframes in the same subplot using matplotlib in Python?

我有一个 geopandas dataframe world ,我使用以下方法创建了它:

import geopandas as gpd

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

我为usachina创建了两个不同的地理数据框,如下所示:

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

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

我想在 map 中将 plot 美国作为蓝色,将中国作为红色。我使用以下代码行绘制了它:

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() 时,label 以下划线开头的艺术家将被忽略。

我无法添加图例。 如何在这个 plot 中添加美国和中国的图例? 是否可以使用 geopandas 和 matplotlib?

我从未使用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()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM