2016-11-08 161 views
1

考慮一個包含多對點的地圖。使用ggplot2,你如何用線段連接每一對點?R ggplot2:繪製連接地圖上點對的多條線段

請考慮以下可重現的示例。

# Load libraries. 
library(ggmap) # for getting map 
library(ggplot2) # for plots 

# Create data frame of points on the map. 
data <- data.frame(p1 = c(1, 3, 5), p2 = c(2, 4, 6), 
        lat_p1 = c(37.78, 37.75, 37.73), 
        lon_p1 = c(-122.41, -122.40, -122.405), 
        lat_p2 = c(37.77, 37.75, 37.72), 
        lon_p2 = c(-122.43, -122.42, -122.415)) 
data 
    p1 p2 lat_p1 lon_p1 lat_p2 lon_p2 
1 1 2 37.78 -122.410 37.77 -122.430 
2 3 4 37.75 -122.400 37.75 -122.420 
3 5 6 37.73 -122.405 37.72 -122.415 

# Get map. 
map <- get_map(location = c(left = -122.523, bottom = 37.69, 
          right = -122.35, top = 37.813), 
       maptype = "roadmap", source = "osm", color = "bw") 

# Plot points on the map. 
ggmap(map) + 
    geom_point(data = data, aes(x = lon_p1, y = lat_p1), color = "red", 
      size = 1) + 
    geom_point(data = data, aes(x = lon_p2, y = lat_p2), color = "purple", 
      size = 1) 

特別是,如何用線段連接圖上的紅色和紫色點?

有幾個相關的問題使用geom_line()通過多個點繪製單個線段。不過,我還沒有看到過這樣的帖子。

enter image description here

回答

3

下面是修改數據幀以獲得所需的情節中的溶液。

# Load libraries (same as before). 
library(ggmap) # for getting map 
library(ggplot2) # for plots 

# Modify the original data frame. 
data2 <- data.frame(point = c(1, 3, 5, 2, 4, 6), 
        pair = c('A', 'B', 'C', 'A', 'B', 'C'), 
        color.group = c('foo', 'foo', 'foo', 'bar', 'bar', 'bar'), 
        lat = c(37.78, 37.75, 37.73, 37.77, 37.75, 37.72), 
        lon = c(-122.41, -122.40, -122.405, -122.43, -122.42, -122.415)) 
data2 
    point pair color.group lat  lon 
1  1 A   foo 37.78 -122.410 
2  3 B   foo 37.75 -122.400 
3  5 C   foo 37.73 -122.405 
4  2 A   bar 37.77 -122.430 
5  4 B   bar 37.75 -122.420 
6  6 C   bar 37.72 -122.415 

# Get map (same as before). 
map <- get_map(location = c(left = -122.523, bottom = 37.69, 
          right = -122.35, top = 37.813), 
       maptype = "roadmap", source = "osm", color = "bw") 

# Plot map with line segments. 
ggmap(map) + 
    geom_point(data = data2, aes(x = lon, y = lat, color = color.group)) + 
    geom_line(data = data2, aes(x = lon, y = lat, group = pair)) 

enter image description here