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

时间:2013-05-05 22:09:14

标签: 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 = 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 = 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 = 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")

到目前为止,一切都按预期工作,我得到一张漂亮的地图:

enter image description here

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:26)

我不是100%确定这是你想要的,但这就是我理解它的方法。如果我们将一些未使用的geomxx.sub1.df中的任何数据进行映射,但在图中隐藏它,我们仍然可以获得该geom的图例。在这里,我使用了geom_point,但您可以将其他用作。{/ p>

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")

enter image description here

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

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

enter image description here

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

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

相关问题