ggplot:如何基于列连接点

时间:2017-05-27 02:05:05

标签: r ggplot2

假设我有关于客户和商店的地理数据,以及客户上次购买的商店。我想绘制客户和商店(根据他们的坐标)并将客户与他们各自的商店联系起来。

这是一个玩具数据集:

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商店的所有客户及其点。我怎么能这样做?

1 个答案:

答案 0 :(得分: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