簡體   English   中英

ggplot:如何基於列連接點

[英]ggplot: How to connect points based on columns

假設我具有有關客戶和商店的地理數據,以及客戶最后一次在哪家商店購物。 我想繪制客戶和商店(根據他們的坐標),並將客戶與其各自的商店聯系起來。

這是一個玩具數據集:

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))

在此處輸入圖片說明

所以我要做的是使用geom_line()或geom_segment()等將S1商店的所有客戶與其點連接起來。 我怎樣才能做到這一點?

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))

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM