0

Suppose that I have geographic data about customers and stores and also in which store the customer made his last purchase. I want to plot customers and stores (according to their coordinates) and connect customers with their respective stores.

Here's a toy dataset:

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

So I want to do is to connect all customers of S1 store with its point using geom_line() or geom_segment() and so on. How can I do that?

1
  • @MikeH. if I add a geom_line after the first geom_point it will connect the customers within the same store but not them with their stores. Commented May 27, 2017 at 2:16

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.