我有一张智利 map (http://labgeo.ufro.cl/fichas/chile_geo/ficha_cl_geo.html 第一个链接,上面写着“智利大陆”),我想绘制它并添加一些我有纬度和经度数据的中心点。
我是 geopandas 和 matplotlib 的新手,但我设法使用这篇文章中 matplotlib 的建议答案将 map 绘制成不同颜色的点:Color by Column Values in Matplotlib
这是我的代码:
#Loading data, since I am making the coordinates up they won´t fit the map nicely but you will get the idea
map_= gpd.read_file("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)
# creating color map for categories
categories = np.unique(geo_df_["id"])
colors = np.linspace(0, 1, len(categories))
colordict = dict(zip(categories, colors))
#matching it to the geopandas df
geo_df_["Color"] = geo_df_["id"].apply(lambda x: colordict[x])
#plotting
geo_df_.plot(ax=map_.plot(figsize=(40, 30)), marker='o', c =geo_df_.Color, markersize=100)
我不能尝试不同的东西是传说出现。
Generating Legend for geopandas plot
到目前为止,我唯一能做的就是通过在末尾添加 .legend() 来显示带有颜色编号的 id 字典,如下所示:
geo_df_.plot(ax=map_.plot(figsize=(40, 30)), marker='o', c =geo_df_.Color, markersize=100).legend()
.但我收到这个错误
No handles with labels found to put in legend.
但是当我将颜色字典作为参数传递时,它会在图例中显示一个点。
我想实现的是这样的传奇:
取自这篇文章:Control ggplot2 legend look without affecting the plot
我的理想传说是在侧面有一个正方形,所有彩色点都用它们代表的 id 中心标识。例如黄点:(中心)5,紫点:8,等等。
我所管理的只是一个点,它显示整个字典如下:
最佳答案
请勿使用 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')
关于python - 将图例添加到 geopandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396901/