R - adding legend to ggmap (ggplot2) while using annotate

旧街凉风 提交于 2019-12-20 17:28:54

问题


FYI: I'm fairly new to ggplot2 and ggmap so I apologize for the sloppy code but it is the only way I've been able to plot sets of groups of points where each group has it's own color. Also my os is ubuntu.

I'm trying to add a legend, to a ggmap object and in particular a legend with a continuos gradient transitioning the colors. Any advice? I've tried the legend attribute in ggmap but it doesn't seem to be working. Below is what I have so far.

syd = get_map(location = center, zoom = zoom, maptype = type,color = "bw")

(SYDmap = ggmap(syd, extent = "panel",legend="right")+ annotate('point',x=lng[[1]],xend=max(lng[[1]]),y=lat[[1]],yend=max(lat[[1]]),colour=colorval[1],cex=cexval,pch=pchval))

for(i in 2:(topnum - 1))
  SYDmap<- SYDmap + annotate('point',x=lng[[i]],xend=max(lng[[i]]),y=lat[[i]],yend=max(lat[[i]]),colour=colorval[i],cex=cexval,pch=pchval)

i=topnum;  (SYDmap <-   SYDmap + annotate('point',x=lng[[i]],xend=max(lng[[i]]),y=lat[[i]],yend=max(lat[[i]]),colour=colorval[i],cex=cexval,pch=pchval)) + guides(fill = "colourbar")

回答1:


Instead of using annotate, here's a method that adds a point layer using geom_point. Almost any geom can be added to a ggmap object as it would be added to a ggplot object. Because Size (see the contents of the df data frame below) is a colour aesthetic in the call to geom_point, the legend is generated automatically.

library(ggmap)

# Get a map - A map of Canberra will do
ACTmap = get_map(c(149.1, -35.325), zoom = 12, source = "google", maptype = "roadmap")

# A data frame of lon and lat coordinates and the variable Size
df = data.frame(lon = c(149.0307, 149.1326, 149.089, 149.048, 149.0965),
            lat = c(-35.3892, -35.28225, -35.34005, -35.34857, -35.34833),
            Size = c(1,2,3,4,5))

# Draw the map
ACTmap = ggmap(ACTmap)

# Add the points
ACTmap = ACTmap + geom_point(data = df, aes(x = lon, y = lat, colour = Size), 
      alpha = 0.6,  size = 10)

# Change the legend
ACTmap + scale_colour_continuous(low = "red", high = "blue", space = "Lab", guide = "colorbar")



来源:https://stackoverflow.com/questions/10918102/r-adding-legend-to-ggmap-ggplot2-while-using-annotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!