簡體   English   中英

向 GeoPandas 圖例添加自定義名稱

[英]Adding custom names to a GeoPandas legend

我有一個 shapefile,它有一個屬性表,其中有一列我想制作地圖/繪圖。 屬性值是數字(整數)。 我對 map 和 colors 和我想要這些整數的名稱做了兩個 dicts。

Palette = {0: 'black',
           20: '#FFBB22',
           30: '#FFFF4C',
           40: '#F096FF',
           80: '#0032C8',
           90: '#0096A0',
           112: '#009900',
           114: '#00CC00',
           116: '#007800',
           124: '#A0DC00',
           126:'#648C00'}

names  = {0: 'NAN',
           20: 'Shrubs',
           30: 'Herbaceous',
           40: 'Cultivated',
           80: 'Permanent Water',
           90: 'Herbaceous Wetland',
           112: 'Closed Forest: Evergreen',
           114: 'Closed Forest: Deciduous broad leaf',
           116: 'Closed forest: Other',
           124: 'Open forest: Deciduous broad leaf',
           126:'Open forest: Other'}

但是,雖然我可以將 map 和 colors 設置為正確的值,但我無法讓圖例顯示正確的名稱。 圖例顯示為空,我收到一條消息“找不到帶有標簽的句柄放入圖例”

我的代碼是:

fig, ax = plt.subplots(figsize=(5, 5))

# Loop through each attribute value and assign each
# with the correct color & width specified in the dictionary
for ctype, data in map_df.groupby('landcovermode'):
    color = Palette[ctype]
    label = names[ctype]
    data.plot(color=color,
          ax=ax,
          label=label,legend=True)


# Place legend in the lower right hand corner of the plot
ax.legend(loc='lower right',
      fontsize=15,
      frameon=True)

ax.set_axis_off()

如何讓圖例從字典中讀取我的標簽?

官方參考已被編輯以解決您的問題。 我對 geopandas 還是很陌生,並且很難使用它。 對於我想要繪制的目標點,我可以處理列表中的 colors,但我無法處理列表中的圖例標簽。 所以我為每個案例創建了一個臨時 gdf 並創建了圖表。 數據格式是數據框和列表,但我覺得可以支持。

import pandas as pd
import geopandas
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
     'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
     'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],
     'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})

gdf = geopandas.GeoDataFrame(
    df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude))

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
colors = ['blue','green','red','black','yellow']

ax = world[world.continent == 'South America'].plot(color='white', edgecolor='black', figsize=(10,10))

for idx, row in gdf.iterrows():
    tmp = df.iloc[idx].to_frame().T
    gdf = geopandas.GeoDataFrame(tmp, geometry=geopandas.points_from_xy(tmp.Longitude, tmp.Latitude))
    gdf.plot(ax=ax, color=colors[idx], label=row['City'], markersize=100, legend=True)

ax.legend(loc='lower right', fontsize=12, frameon=True) 
ax.set_axis_off()

plt.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM