2014-06-08 27 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")