[英]How can I add legend while plotting multiple geopandas dataframes in the same subplot using matplotlib in Python?
I have a geopandas dataframe world
which I created using:我有一个 geopandas dataframe world
,我使用以下方法创建了它:
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
I created two different geodataframes for usa
and china
as shown below:我为usa
和china
创建了两个不同的地理数据框,如下所示:
usa = world[world.name == "United States of America"]
china = world[world.name == "China"]
I want to plot the USA as blue and China as red in the map. I plotted it using the following line of code:我想在 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()
I want to add legends stating blue for the USA and red for China.我想添加说明美国为蓝色,中国为红色的图例。 Therefore, I gave labels as shown in the code above.因此,我给出了上面代码中所示的标签。 However, I get the following warning:但是,我收到以下警告:
No artists with labels found to put in legend.找不到带有标签的艺术家放入图例。 Note that artists whose label start with an underscore are ignored when legend() is called with no argument.请注意,当不带参数调用 legend() 时,label 以下划线开头的艺术家将被忽略。
I am not able to add the legend.我无法添加图例。 How can I add the legends for the USA and China in this plot?如何在这个 plot 中添加美国和中国的图例? Is it possible using geopandas and matplotlib?是否可以使用 geopandas 和 matplotlib?
I never used geopandas
, however looking at the result is appears that those filled areas are PathCollection
, which are not supported on legends.我从未使用geopandas
,但是从结果来看,这些填充区域似乎是PathCollection
,图例不支持这些区域。 But we can create legend artists:但我们可以创造传奇艺术家:
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.