在GGPLOT2,我怎么可以添加额外的传奇?(In ggplot2, how can I add a

2019-09-02 00:44发布

我试图建立一个地图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")

到现在为止一切正常,我得到一个不错的地图:

我想不过改变是从添加单独的传奇数据xx.sub1.df -因为所有的多边形只是充满了灰色的,我希望这将是一个额外的条目。

我怎样才能做到这一点?

Answer 1:

我不是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")

现在,我们只需要改变的传说点的大小和形状,并更改图例的名称(感谢@DizisElferts谁证明了这一点前面 )。

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

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

如果这不是你以后,让我知道!



文章来源: In ggplot2, how can I add additional legend?
标签: r ggplot2