首页 > 解决方案 > 无法为 GeoDataFrame 点着色

问题描述

我想绘制整个巴黎的位置并按列类型为它们着色。我还想绘制与位置类型相关的图例。我可以创建 GeoDataframe,绘制整个巴黎的位置。但是我无法指定地图上点的颜色。此外,我必须单独创建一个图例,然后将其应用于情节。

如何让绘图点的颜色与图例列相匹配?

在此处输入图像描述

代码:

paris = gpd.read_file(shape_filepath)
ax = paris.plot(figsize=(40,10), linewidth=1, edgecolor='white', color='lightgrey')
ax.axis('off')
ax.set_title("Casino Banner Stores Paris", fontdict={"fontsize": "25","fontweight" : "5"})

xl = r"summary.xlsx"
df =pd.read_excel(xl,sheet_name = "paris_stores_and_metro_chart")
df = df.dropna()

#Create Points for Shape file - these are long lat pairs
geometry =[Point(xy) for xy in zip(df["lng"],df["lat"])]
crs ={'init':'espg:4326'}
#Create GeoDataFrame
stores =gpd.GeoDataFrame(df,crs=crs,geometry=geometry)
stores.plot(ax=ax,figsize=(40,10), column=stores['colour'], cmap=None)


legend_elements =     [  
                        Line2D([0],[0], markerfacecolor ='#0000ff',marker='o', color='w',label ='casino'),
                        Line2D([0],[0], markerfacecolor ='#3366ff',marker='o', color='w', label ='fanrpix'),
                        Line2D([0],[0], markerfacecolor ='#00e6b8',marker='o',  color='w',label ='geant'),
                        Line2D([0],[0], markerfacecolor ='#e6e600',marker='o', color='w', label ='leader price'),
                        Line2D([0],[0], markerfacecolor ='#e65c00',marker='o', color='w', label ='metro station'),
                        Line2D([0],[0], markerfacecolor ='#ff00ff',marker='o', color='w', label ='monoprix'),
                        Line2D([0],[0], markerfacecolor ='#e60000',marker='o', color='w', label ='naturalia')
                    ]


ax.legend(handles=legend_elements, fontsize =20)

在此处输入图像描述

标签: pythonmatplotlibgeopandas

解决方案


理想情况下,您必须使用 GeoPandas 0.6.3 或 0.7.0。然后你应该能够在绘图期间将你的colour列传递给color关键字,并且 geopandas 应该将分配给每一行的颜色映射到它的几何图形。请参阅以下说明该行为的代码段:

import geopandas as gpd
from shapely.geometry import Point

g = [Point(0, 0), Point(1, 0), Point(1,1), Point(0.5, .5)]
gdf = gpd.GeoDataFrame(geometry=g)
gdf['colour'] = ['#0000ff', 'r', '#0000ff', 'k']
gdf.plot(color=gdf.colour)

结果图

在您的情况下,这应该可以解决问题:

stores.plot(ax=ax, figsize=(40,10), color=stores['colour'])

如果没有,那么您要么使用的是旧版本的 geopandas,要么存在错误。在这种情况下,请报告


推荐阅读