2014-02-28 57 views
2

我想將底圖添加到我的圖中,該圖將三個SpatialPointDataFrame可視化。 我已經試過了maptools以及RgoogleMaps軟件包,但都沒有按照我想要的方式工作。
我的問題:SpatialPointDataFrames不繪製在GoogleMaps背景地圖上。使用R將地圖添加到SpatialPointDataFrames

的最小例如:

用下面的例子含量city.csv:

FID,city,POINT_X,POINT_Y 
0,New York,-73.996786,40.720813 
1,Newark,-74.172237, 40.732196 

將R代碼:

# Load packages 
library(RgoogleMaps) 
library(sp) 

# load .csv file 
city= read.csv("city.csv", header = TRUE) 

# convert to SpatialPointDataFrame 
coordinates(city) <- c("POINT_X", "POINT_Y") 
proj4string(city) <- CRS("+proj=longlat +datum=WGS84") 

# use RgoogleMaps 
gc <- geocode('new york, usa') 
center <- as.numeric(gc) 
ggmap(get_googlemap(center = center, color = 'bw', scale = 4), fullpage = T) 
# Plot the city dataset 
plot(city, pch = 22, col="black", bg= "yellow", cex = 1.5, add = TRUE) 

結果應該是與背景地圖的圖和這兩點,但這些點不是在地圖上繪製的。 是否有地理編碼問題或者我錯過了什麼?可以結合ggmap和plt函數嗎?

任何幫助非常感謝!

回答

3

使用ggplot2進行這種工作要容易得多,您可以將點,多邊形,2densities等添加到ggmap圖層。

library(RgoogleMaps) 
library(sp) 
library(ggplot2) 
library(ggmap) 

P是SpatialPointsDataFrame對象:

DB <- data.frame(FID=P$FID, city=P$city) 
DB <- cbind(DB, [email protected]) 


DB <- data.frame(FID=c(0,1), city=c("New York", "Newark"), POINT_X=c(-73.996786,-74.172237), POINT_Y=c(40.720813,40.732196)) 
gc <- geocode("new york, usa") 
center <- as.numeric(gc) 
G <- ggmap(get_googlemap(center = center, color = 'bw', scale = 4), extent = "device") 
G1 <- G + geom_point(aes(x=POINT_X, y=POINT_Y),data=DB, color="red", size=5) 
plot(G1) 

這是輸出:

enter image description here

+0

謝謝您的回答。不幸的是,我還有一些問題需要加入我的SpatialPointDataFrame。 我想通過使用「DB <城市,其中城市是一個SpatialPointDataFrame然後我得到兩個錯誤:首先我從行」G < - ggmap ...「得到一個錯誤:警告消息: 整頁和擴展語法不推薦使用,使用範圍 在此之後,從「G1 < - G + geom_point ...」出現另一個錯誤:錯誤:ggplot2不知道如何處理類SpatialPointsDataFrame的數據 – schlomm

+0

好的。如果網格圖形不知道如何提取空間座標到繪圖,那麼我們可以從SpatialPolygonsDataFrame轉換爲data.frame。我編輯了原始答案以滿足這個變化 – eclark

+0

非常感謝。像一個魅力工作:)左邊的兩個問題:1.)所以...不是可能使用ggplot2的SpatialPointDataFrames,我必須使用傳統的data.frames? 2.)使用ggplot2設計地圖有沒有很好的參考?就像符號類型等可能的參數一樣簡短的概述?直到現在我只知道如何設置顏色和尺寸。 – schlomm

0

這些是兩個不同的框架(網格和基礎圖形)。雖然,兩者的結合可能是可能的,但我建議堅持使用ggplot。

您可以使用geom_point()輕鬆添加點,例如,請參閱答案here