繁体   English   中英

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

[英]In ggplot2, how can I add additional legend?

我正在尝试使用来自不同数据帧的数据在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")

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

在此输入图像描述

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

我怎样才能做到这一点?

我不是100%肯定这是你想要的,但这就是我理解它的方法。 如果我们将一些未使用的geom与来自xx.sub1.df任何数据进行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")

在此输入图像描述

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

p2 + guides(size=guide_legend("Source", override.aes=list(shape=15, size = 10)))

在此输入图像描述

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM