在ggplot2中,如何添加其他图例?

rad*_*dek 21 r ggplot2

我正在尝试ggplot2使用来自不同数据帧的数据构建映射.

library(maptools)

xx <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1], IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))

xx.sub1 <- subset(xx, xx$FIPSNO < 37010)
xx.sub2 <- subset(xx, xx$FIPSNO > 37010)

xx.sub1@data$id <- rownames(xx.sub1@data)
xx.sub1.points <- fortify(xx.sub1, region="id")
xx.sub1.df = plyr::join(xx.sub1.points, xx.sub1@data, by="id")

xx.sub2@data$id <- rownames(xx.sub2@data)
xx.sub2.points <- fortify(xx.sub2, region="id")
xx.sub2.df = plyr::join(xx.sub2.points, xx.sub2@data, by="id")

ggplot(xx.sub2.df) + 
  aes(long, lat, fill = (SID79/BIR79)*1000, group = group) + 
  geom_polygon() + geom_path(color="grey80") +
  coord_equal() + 
  scale_fill_gradientn(colours = RColorBrewer::brewer.pal(7, "YlOrBr")) +
  geom_polygon(data = xx.sub1.df, fill = "grey50") + 
  geom_path(data = xx.sub1.df, color="grey80") +
  labs(fill = "Mapped value", title = "Title")
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都按预期工作,我得到一个很好的地图:

在此输入图像描述

然而,我想改变的是为数据添加单独的图例xx.sub1.df- 因为所有多边形都只是填充灰色,我希望它将是一个额外的条目.

我怎样才能做到这一点?

ale*_*han 27

我不是100%肯定这是你想要的,但这就是我理解它的方法.如果我们将一些未geom使用的数据映射到任何数据中xx.sub1.df,但在图中使其不可见,我们仍然可以得到一个图例geom.在这里我已经习惯了geom_point,但你可以把它变成其他人.

p <- ggplot(xx.sub2.df) + 
  aes(long, lat, fill = (SID79/BIR79)*1000, group = group) + 
  geom_polygon() + geom_path(color="grey80") +
  coord_equal() + 
  scale_fill_gradientn(colours = brewer.pal(7, "YlOrBr")) +
  geom_polygon(data = xx.sub1.df, fill = "grey50") + 
  geom_path(data = xx.sub1.df, color="grey80") +
  labs(fill = "Mapped value", title = "Title")

#Now we add geom_point() setting shape as NA, but the colour as "grey50", so the 
#legend will be displaying the right colour

p2 <- p + geom_point(data = xx.sub1.df, aes(size="xx.sub1", shape = NA), colour = "grey50")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我们只需要改变图例上点的大小和形状,并更改图例的名称(感谢前面演示过的 @DizisElferts ).

p2 + guides(size=guide_legend("Source", override.aes=list(shape=15, size = 10)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当然,您可以更改标签的工作方式或任何突出显示内容的方式.

如果这不是你想要的,请告诉我!