为 geopandas 添加图例

Isa*_*Isa 9 python matplotlib legend shapefile geopandas

我有一张智利地图(http://labgeo.ufro.cl/fichas/chile_geo/ficha_cl_geo.html第一个链接上面写着“智利大陆”),想绘制它并添加一些我有纬度的中心点经度数据。

\n\n

我是 geopandas 和 matplotlib 的新手,但我设法使用这篇文章中 matplotlib 的建议答案以不同颜色的点的形式绘制地图:Color by Column Values in Matplotlib

\n\n

这是我的代码:

\n\n
#Loading data, since I am making the coordinates up they won\xc2\xb4t fit the map nicely but you will get the idea\n\nmap_= gpd.read_file("cl_continental_geo.shp")\ngeo_df_ = pd.DataFrame({"id":np.random.randint(20, size=133) ,"Latitude": np.random.normal(-34.406922,7.819504, 133), "Longitud": np.random.normal(-71.243350,1.254126, 133)})\n\ngeometry =[Point(xy) for xy in zip( geo_df_["Longitud"],geo_df_["Latitude"])]\ngeo_df_ =gpd.GeoDataFrame(geo_df_, crs={"init":"epsg:4326"},geometry= geometry)\n\n# creating color map for categories\ncategories = np.unique(geo_df_["id"])\ncolors = np.linspace(0, 1, len(categories))\ncolordict = dict(zip(categories, colors))\n\n#matching it to the geopandas df\ngeo_df_["Color"] = geo_df_["id"].apply(lambda x: colordict[x])\n\n#plotting    \ngeo_df_.plot(ax=map_.plot(figsize=(40, 30)), marker=\'o\', c =geo_df_.Color, markersize=100)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我可以\xc2\xb4t尝试不同的事情是出现的图例。

\n\n
    \n
  • 我尝试添加 legend=True
  • \n
  • 我尝试先通过定义 ax 来做到这一点,但我可以\xc2\xb4t 设法正确地提供数据来创建绘图,但最终什么也没有。
  • \n
  • 尝试了这个解决方案,但我的 shp 文件只有一行包含多多边形信息,并且我不\xc2\xb4t 知道如何创建建议的交叉数据框\n为 geopandas 图生成图例
  • \n
\n\n

到目前为止,我唯一能做的就是通过在末尾添加 .legend() 来显示带有颜色编号的 ids 字典:\n geo_df_.plot(ax=map_.plot(figsize=(40, 30)), marker=\'o\', c =geo_df_.Color, markersize=100).legend()。\n但是我收到这个错误

\n\n
\n

未发现带有标签的句柄可放入图例中。

\n
\n\n

但是当我将颜色字典作为参数传递时,它会在图例中显示一个点。

\n\n

我想要实现的是这样的传奇:

\n\n

在此输入图像描述

\n\n

摘自这篇文章:控制 ggplot2 图例外观而不影响绘图\n我理想的图例是在侧面有一个正方形,所有彩色点都用它们代表的 id 中心标识。例如黄点:(中心)5,紫点:8,等等。

\n\n

我所管理的只是一个点,它显示整个字典如下:

\n\n

带有字典图例的地图部分示例

\n

mar*_*eis 11

不使用c,但是column。然后legend=True会做一些技巧来展示图例,并categorical=True给你你想要的。在这种特定情况下,您可能会用完颜色,因此如果您希望所有颜色都不同,则必须设置另一个颜色图 ( cmap='')

map_= gpd.read_file("/Users/martin/Downloads/cl_continental_geo/cl_continental_geo.shp")
geo_df_ = pd.DataFrame({"id":np.random.randint(20, size=133) ,"Latitude": np.random.normal(-34.406922,7.819504, 133), "Longitud": np.random.normal(-71.243350,1.254126, 133)})

geometry =[Point(xy) for xy in zip( geo_df_["Longitud"],geo_df_["Latitude"])]
geo_df_ =gpd.GeoDataFrame(geo_df_, crs={"init":"epsg:4326"},geometry= geometry)

#plotting    
ax = map_.plot(figsize=(40, 30))
geo_df_.plot(ax=ax, marker='o', column='id', categorical=True,
             markersize=100, legend=True, cmap='tab20')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述