Plotting coordinates of multiple points at google map in R

元气小坏坏 提交于 2019-11-30 05:30:59

Rather than request a map of 'Switzerland' from google, you should request a map of a specific location by specifying a longitude/latitude and desired zoom (and maybe scale). Then you won't have to use coord_map() and blur your image.

Here are the basics, you can play around with colors and sizes as in any ggplot:

library(ggplot2)
library(ggmap)

# copying text off screen
# since the OP did not use dput()
data<-read.table("clipboard")

# reformat
data=data[,-1]
names(data)=c("lon","lat","id")
data$lon <- as.numeric(gsub('[\\(\\)\\,]', '', data$lon))
data$lat <- as.numeric(gsub('[\\(\\)\\,]', '', data$lat))

head(data)
#       lon     lat id   
# 1 7.17350 45.8688  2  
# 2 7.17254 45.8689  3 
# 3 7.17164 45.8692  4 
# etc

# determine a reasonable center for map, 
# this could fail in some places (near poles, 180th meridian)
# also google appears to shift things slightly
 center = paste(min(data$lat)+(max(data$lat)-min(data$lat))/2,
                min(data$lon)+(max(data$lon)-min(data$lon))/2, sep=" ")

# get map image from google
map <- get_map(location = center, zoom = 11, maptype = "terrain", 
       source = "google")

# start a ggplot. it won't plot til we type p
p <- ggmap(map)

# add text labels, these will overlap
p <- p + geom_text(data=data,aes(x = lon, y = lat, 
         label = id),
         colour="white",size=4,hjust=0, vjust=0)+
    theme(legend.position = "none") 

# add points last so they are on top
p <- p + geom_point(data=data,aes(x=lon, y=lat),colour="white",size=2)

# display plot
p 

This naturally is described in ?get_map and ?get_googlemap.

One of the problems with plotting of your points is that if you use zoom=10 in function get_map() then your points are outside the map and they want be plotted, so I used zoom=5 instead.

    library(ggmap)
    map <- get_map(location = 'Switzerland', zoom = 5, 
        maptype = "terrain",  source = "google") 

For the plotting of map I used function ggmap(). To add points geom_point() can be used. For this purpose your sample data were saved as data frame df with columns x, y and id. To zoom closer to points coord_map() can be used.

    p <- ggmap(map)
    p <- p +geom_point(data=df,aes(x=x,y=y))+
      coord_map(xlim=c(7,8),ylim=c(45.5,46))
    print(p)

If you need to add labels to each point then add this line to map p

annotate("text",x=df$x,y=df$y,label=df$id)

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