Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot geom_segment on ggmap object in R - lines not appearing

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?

like image 488
Marta Karas Avatar asked Jun 08 '14 17:06

Marta Karas


2 Answers

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))
like image 152
Didzis Elferts Avatar answered Nov 15 '22 05:11

Didzis Elferts


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")
like image 45
Marcio Jasinski Avatar answered Nov 15 '22 07:11

Marcio Jasinski