2017-05-27 5 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

だから私はやりたいように(geom_line()や注意geom_segmentを使用して、その時点でS1ストアのすべての顧客を接続)とすることです。どうやってやるの?

+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

関連する問題