Add legend to ggmap

南笙酒味 提交于 2019-12-11 18:07:17

问题


I am trying to add a legend to a plot generated by ggmap package in R. The dataset I am working with is

    Latitude  Longitude  amount
    61.37072 -152.40442  436774
    32.80667  -86.79113 3921030
    34.96970  -92.37312 1115087
    33.72976 -111.43122 5068957

The code I am using is

library(ggplot2)
library(ggmap)

MyMap <- get_map(location = c(lon = -96.5, lat = 40.68925), zoom = 4,maptype = "terrain", scale = 2)
ggmap(MyMap)+ 
geom_point(data = data,aes(x = Longitude , y = Latitude ),size=sqrt(data$amount)/800,col='darkred', shape = 19,alpha = .5) 

Now I want to add legend to this plot. The legend should show the sizes of the circles on the map correspond to certain amount. How can I do it?


回答1:


The size argument should be included within the aes() section of the geom_point function, as follows:

plot <- ggmap(MyMap) + 
  geom_point(data = data,aes(x = Longitude , y = Latitude, size=amount), col='darkred', shape = 19,alpha = .5)
plot 

If you want to have further customisation of the scale, you can use the optional argument scale_size_area() to choose the breaks and labels for the legend. For example:

plot +  scale_size_area(breaks = c(436774, 1115087, 4000000, 5068957),
          labels = c("436774", "1115087", "4000000", "5068957"))

Change Point Size:

If you want to adjust the size of the points, you are better off using the scale_size function, which lets you specify a range:

plot +  scale_size(range = c(5,9))



来源:https://stackoverflow.com/questions/47253773/add-legend-to-ggmap

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