python - 向 GeoPandas 图例添加自定义名称
问题描述
我有一个 shapefile,它有一个属性表,其中有一列我想制作地图/绘图。属性值是数字(整数)。我制作了两个字典来将我想要的颜色和名称映射到这些整数。
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'}
但是,虽然我可以将颜色映射到正确的值,但我无法让图例显示正确的名称。图例显示为空,我收到一条消息“找不到带有标签的句柄放入图例”
我的代码是:
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 还是很陌生,并且很难使用它。对于我想绘制的目标点,我可以处理列表中的颜色,但我无法处理列表中的图例标签。所以我为每个案例创建了一个临时 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()
推荐阅读
- laravel - Laravel 中路由的多个中间件。数组还是多个参数?
- c++ - 你能告诉我给出的代码是如何到达那个输出的吗?
- firebase - 可以存储在 Firestore 文档字段中的最长字符串值是多少?
- python-3.x - 如何使用scrapy从主要列表页面以及该特定列表的详细信息页面中抓取数据
- hyperledger-fabric - 在 Hyperledger Fabric 中注册用户时角色有什么用
- hadoop - 连接到端口 10000 的 Hive 问题
- javascript - 如何将 json 编码的 php 变量转换为同一文件中的 JavaScript JSON 对象
- oop - 哪种设计(使用 OOP)更好?外部化还是内部化日志记录?
- nswag - 使用 NSwagStudio 时在运行时指定 API Endpoint
- ios - UIScrollview 的可点击内容不起作用