2014-06-08 28 views
4

我想在我的ggmap對象(它是一個ggplot2對象,據我瞭解)繪製線條(確切地說:geom_segment元素)。在R中繪製ggmap對象上的geom_segment不顯示

我使用以下代碼:

library(ggmap) 

mapImageData <- get_map(location = c(lon = (16.8 + (17.2-16.8)/2), 
            lat = (51 + (51.2-51)/2)), 
         color = "color", 
         source = "google", 
         maptype = "roadmap", 
         zoom = 11) 

ggmap(mapImageData, extent = "device", ylab = "Latitude", xlab = "Longitude") + 
geom_segment(aes(x = 51, y = 16.8, xend = 51.2, yend = 17.2)) 

一種清澈地圖正在繪製:

enter image description here

無線(從geom_segment正在出現。我究竟做錯了什麼?

回答

7

緯度值對應於y值和經度x值。所以你必須改變geom_segment()中的x和y值。

ggmap(mapImageData, extent = "device", ylab = "Latitude", xlab = "Longitude") + 
     geom_segment(aes(y = 51, x = 16.8, yend = 51.2, xend = 17.2)) 
+0

所以啞巴是我的問題...謝謝! = D –

+0

特別是,如果有人遇到同樣的問題,使用aes時要小心!如果您指定新數據(例如您想繪製獨立於原始數據的段),則需要aes()。這就是爲什麼它不適合我。感謝這個例子,你也解決了我的問題! –

2

另外,您也可以使用geom_path,讓你可以繪製一些GPS點爲線:

gpsData <- read.csv("001.txt") 
    lonCenter <- mean(gpsData[[3]], na.rm = TRUE) 
    latCenter <- mean(gpsData[[4]], na.rm = TRUE) 

    map <- get_map(location = c(lon = lonCenter, lat = latCenter), zoom = 10) 

    dataFrame <- structure(
    list(
     taxiId = gpsData[[1]], 
     longitude = gpsData[[3]], 
     latitude = gpsData[[4]]  
    ), 
    .Names = c("id", "longitude", "latitude"), class = "data.frame" 
) 

    mapImage <- ggmap(map) + 
    geom_path(
     data = dataFrame, 
     aes(x = longitude, y = latitude, fill = "red", colour = "red", alpha = 1/3), 
     size = 3, shape = 21 
    ) + 
    guides(
     fill=FALSE, alpha=FALSE, size=FALSE, colour = FALSE 
    ) 

    ggsave(mapImage, filename = "001.png")