[英]Plotting multiple curves with a legend using subplot on matplotlib animation
[英]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'))
我為usa
和china
創建了兩個不同的地理數據框,如下所示:
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.