2017-05-27 49 views
0

假設我有關於客戶和商店的地理數據,以及客戶上次購物的地點。我想繪製客戶和商店(根據他們的座標),並將客戶與他們各自的商店連接起來。ggplot:如何根據列連接點

這裏有一個玩具數據集:

library(tidyverse) 
library(ggrepel) 

customer.data <- data.frame(
    customer = letters[1:12], 
    store = rep(paste0("S", 1:3), 4), 
    customer.lat = rnorm(12), 
    customer.lon = rnorm(12)) 

store.data <- data.frame(
    customer = NA 
    store = paste0("S", 1:3), 
    store.lat = rnorm(3), 
    store.lon = rnorm(3) 
) 


data <- left_join(customer.data, store.data, by = "store") %>% 
    arrange(store, customer) 

ggplot(data, aes(x = customer.lat, y = customer.lon, group = store)) + 
    geom_point(color = "blue") + 
    geom_point(aes(x = store.lat, y = store.lon), color = "red") + 
    geom_text_repel(aes(label = store)) 

enter image description here

所以我希望做的是S1店的所有客戶提供其使用點geom_line()或geom_segment()等連接。我怎樣才能做到這一點?

+0

@MikeH。如果我在第一個geom_point之後添加geom_line,它將連接同一商店內的顧客,但不會將他們連接到他們的商店。 – iatowks

回答

3
ggplot(data, aes(x = customer.lat, y = customer.lon)) + 
    geom_point(aes(color = store)) + 
    geom_point(aes(x = store.lat, y = store.lon, color = store), size = 4) + 
    #geom_text_repel(aes(label = store)) + 
    geom_segment(aes(x = customer.lat, y = customer.lon, 
        xend = store.lat, yend = store.lon, 
        color = store)) 

enter image description here