简体   繁体   中英

ggplot2 adding extra info in legend

I got a map of Canada

library(ggmap)
mp = get_map(location = "Canada", maptype="satellite", color="color")

then I want to plot 14 points on the map:

p = ggmap(mp) + 
    geom_point(data=GPScor, x=lon, y = lat, col="red", size =2.1) + 

then i want to number the points on thee graph:

geom_text(data=GPScor, aes(x=decLon, y=decLat,label=lbl),
    adj=2,offset=1, color="white", size=4, hjust=4) 

I can't find the way how to create a legend where it will list the number with the corresponding name of the point: something like

1: "name of point1"
2: "name of point2 "   

Sorry I initially misread the question You should include the name in an aes for your geom_point .

dat<-data.frame(name=c("a","b","c"), x=1:3, y=1:3)

ggplot(dat, aes(x=x, y=y))+
  geom_point(aes(shape=paste(1:3,": point",name)))+
  geom_text(aes(x=x,y=y+0.07), label=1:3)+
  labs(shape="locations")

If you don't actually want them to be displayed with different shapes, them just override it using scale_shape_manual and set an arbitrary value.

  scale_shape_manual(values=rep(1,3))

Below put all together

dat<-data.frame(name=c("a","b","c"), x=1:3, y=1:3)

ggplot(dat, aes(x=x, y=y))+
  geom_point(aes(shape=paste(1:3,": point",name)))+
  geom_text(aes(x=x,y=y+0.07), label=1:3)+
  scale_shape_manual(values=rep(1,3))+
  labs(shape="locations")

在此处输入图片说明

Here is an example using ggmap explicitly

mp <- get_map(location = "Canada", maptype="satellite", color="color")
dat<-data.frame(lon=c(-106.6, -106.4), lat=c(56.0, 56.2), names=c("1","2"))
  ggmap(mp)+
  geom_point(data=dat, aes(x=lon, y = lat, 
             color=paste(seq_along(dat$lon), ": location", names),
             shape=paste(seq_along(dat$lon), ": location", names)))+
  scale_shape_manual(values=rep(1,nrow(dat)))+
  labs(shape="locations", color="locations")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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