ggmap:'错误:ggplot2不知道如何处理类SpatialPointsDataFrame的数据'

时间:2016-04-02 11:07:29

标签: r ggmap

我想使用ggmap创建地图。我想显示一些点的位置,从具有UTM坐标的数据帧开始。但是,我总是最终得到错误消息:'错误:ggplot2不知道如何处理类SpatialPointsDataFrame'的数据。帮助是非常有用的... o_0

以下是我的例子:

#packages
library(rgeos)
library(maptools) 
library(rgdal)    
library(sp)       
library(ggmap) 

#create data frame with UTM coordinates
Point_ID <- c(1,2)
Easting <- c(519769,518250)
Northing <- c(5767155,5766640)

df <- data.frame(Point_ID, Easting, Northing)

#set spatial coordinates to create a Spatial object
myvars <- c("Easting","Northing")
coords <- df[myvars]
sp = SpatialPoints(coords)

spdf = SpatialPointsDataFrame(sp, df)

#define the projection (UTM coordinates zone 30)
proj4string(spdf)=CRS("++proj=utm +zone=30") 

#transformed to geographic coordinates (latitude/longitude)
spdf<- spTransform(spdf, CRS("+proj=longlat +datum=WGS84"))


#create map
myLocation <- "Hereford" 
myMap <- get_map(location = myLocation, zoom=16, maptype= "satellite")

ggmap(myMap)+
  geom_point(aes(x = lon, y = lat), data = spdf,
             alpha = .5, color="darkred", size = 3)

#Error: ggplot2 doesn't know how to deal with data of class      SpatialPointsDataFrame

1 个答案:

答案 0 :(得分:7)

从SpatialPointsDataFrame

中提取协调
ggmap(myMap)+
geom_point(aes(x = Easting, y = Northing), data = as.data.frame(coordinates(spdf)),
         alpha = .5, color="darkred", size = 3)

注意 - 您提供的两个点不在地图的边缘。