如何使用 matplotlib 绘制地图制作图例?

How to make a legend with matplotlib plotting a map?

我有以下情节:

在这张地图中,您会看到一些带有数字的随机彩色区域。数字是 12、25、34、38 和 43。现在我想在左上角添加一个图例,数字后跟区域名称。像这样:

使用以下命令 ax.annotate(number, xy = ...) 通过 for 循环添加注释(区域中的数字)。有人能告诉我如何在类似于上图的某种图例中添加包含所有数字和文本的图例吗?

数字和名字都在 pandas 数据框中。

fig, ax = plt.subplots(1,1)
fig.set_size_inches(8,8)                      # setting the size

# Plot values - with grey layout

grey_plot = schap.plot(ax = ax, color = 'grey')
schap.plot(ax = grey_plot, column= col1, cmap= 'YlGnBu', legend = True)

    
# Add annotation for every waterschap with a deelstroomgebied
bbox_props = dict(boxstyle="round", fc="w", ec="gray", alpha=0.9,lw=0.4)
for idx, row in schap.iterrows():    
    if not np.isnan(row[col1]):
        string = str(idx)
        ax.annotate(string, xy=row['coords'], color='black',
                     horizontalalignment='center', bbox=bbox_props, fontsize=7)
        

'schap' 是包含所有需要数据的 pandas 数据框。 schap['text'] 包含所有名称。在 for 循环中,这将是 row['text'].

在循环之后你可以简单地添加文本,例如:

ax.text(0.01, 0.99, legend,
    horizontalalignment='left',
    verticalalignment='top',
    transform=ax.transAxes,
    fontsize=8)

其中 legend 可以在循环内更新(desc 是带有描述的列):

legend = ''
#...

#inside your loop
    legend = legend + f"{idx} {row['text'])}\n"

编辑: 具有不同数据(和图例对齐)的示例:

import geopandas
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1,1)
fig.set_size_inches(20,8) 

world.plot(column='gdp_md_est', ax=ax, legend=True)
world['coords'] = world['geometry'].apply(lambda x: x.representative_point().coords[:][0])

bbox_props = dict(boxstyle="round", fc="w", ec="gray", alpha=0.9,lw=0.4)
legend = ''

for idx, row in world.iterrows():
    if row['pop_est'] > 100_000_000:
        plt.annotate(str(idx), xy=row['coords'], color='black',
            horizontalalignment='center', bbox=bbox_props, fontsize=7)
        legend = legend + f"{idx} {row['name']}\n"
        
ax.text(0.01, 0.5, legend,
    horizontalalignment='left',
    verticalalignment='center',
    transform=ax.transAxes,
    fontsize=8);