Plot geom_segment on ggmap object in R - lines not appearing
Asked Answered
M

2

5

I want to plot lines (to be precise: geom_segment element) on my ggmap object (which is a ggplot2 object, as I understand).

I use the following code:

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))

A clear map is being drawn:

enter image description here

but no line (from geom_segment) is appearing. What am I doing wrong?

Muzz answered 8/6, 2014 at 17:57 Comment(0)
K
7

Lattitude values correspond to y values and longitude to x values. So you have to change x and y values in geom_segment().

ggmap(mapImageData, extent = "device", ylab = "Latitude", xlab = "Longitude") + 
      geom_segment(aes(y = 51, x = 16.8, yend = 51.2, xend = 17.2))
Kinsey answered 8/6, 2014 at 18:2 Comment(2)
So dumb was my question... Thank you! =DMuzz
Especially, if someone had the same problem as me, be careful when using aes! If you specify new data (like you want to plot a segment independent of the original data) you need aes(). That's why it wasn't working for me. Thanks for this example, you solved my problem as well!Toombs
I
2

Alternatively you can also use geom_path which allow you to plot several gps points as a line:

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")
Intense answered 3/9, 2015 at 2:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.