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

前端 未结 1 858
北海茫月
北海茫月 2021-02-06 17:09

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 o

相关标签:
1条回答
  • 2021-02-06 18:07

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

    enter image description here

    0 讨论(0)
提交回复
热议问题