geom_sf图例无标签且红点图例叠加问题求解
ggplot2 geom_sf 图例重叠问题解决
问题描述
首次使用geom_sf(结合ggplot2)绘图,基于ggmap和omsdata开发,用两份数据集绘图时,想将红色点添加到现有图例下方,但添加show.legend = "point"后,红点显示在蓝点内部。
原始代码
bl_basemap <- get_map(location = getbb("belluno"), zoom = 9, maptype = 'toner-hybrid', source = 'stamen') ggmap(bl_basemap) + geom_sf(data = geobelluno2cdp, aes(colour = f, size=f), inherit.aes = FALSE) + geom_sf(data = geopnasc, fill = "red", color = "red", inherit.aes = FALSE) + guides(color = guide_legend(override.aes = list(fill = "red")))+ coord_sf(crs = st_crs(4326)) + xlab("LONGITUDINE") + ylab("LATITUDINE") + ggtitle("Belluno (2022)") + theme(plot.title = element_text(hjust = 0.5))
添加show.legend后的代码
ggmap(bl_basemap) + geom_sf(data = geobelluno2cdp, aes(colour = f, size=f), inherit.aes = FALSE) + geom_sf(data = geopnasc, fill = "red", color = "red", inherit.aes = FALSE, show.legend = "point") + guides(color = guide_legend(override.aes = list(fill = "red")))+ coord_sf(crs = st_crs(4326)) + xlab("LONGITUDINE") + ylab("LATITUDINE") + ggtitle("Belluno (2022)") + theme(plot.title = element_text(hjust = 0.5))
解决方案
问题根源是两个图层共享了color图例,导致红点被合并到原有图例项中。要让红点成为独立的图例项,需要给红色点图层单独设置美学映射,再通过guides调整图例显示:
- 给红色点图层添加
aes(fill = "自定义名称"),生成新的独立图例项 - 用
scale_fill_manual指定该图例的颜色为红色 - 通过
guides分别控制color和fill图例的顺序与名称
修改后的代码如下:
bl_basemap <- get_map(location = getbb("belluno"), zoom = 9, maptype = 'toner-hybrid', source = 'stamen') ggmap(bl_basemap) + geom_sf(data = geobelluno2cdp, aes(colour = f, size=f), inherit.aes = FALSE) + # 给红色点添加fill映射,生成独立图例 geom_sf(data = geopnasc, aes(fill = "出生点"), color = "red", inherit.aes = FALSE, show.legend = "point") + # 指定fill图例的颜色 scale_fill_manual(values = "red") + # 调整两个图例的顺序和名称 guides( color = guide_legend(title = "分类"), fill = guide_legend(title = "标记", order = 2) # order=2表示在原有图例下方 ) + coord_sf(crs = st_crs(4326)) + xlab("LONGITUDINE") + ylab("LATITUDINE") + ggtitle("Belluno (2022)") + theme(plot.title = element_text(hjust = 0.5))
补充说明
- 若不需要原有
color图例的fill覆盖效果,可删除原代码中的override.aes = list(fill = "red"),按需调整 order参数控制图例排列顺序,数值越大,图例位置越靠下
内容的提问来源于stack exchange,提问作者veronica
相关产品推荐
相关产品推荐

