简体   繁体   中英

Connecting points in ggmap based on an ID

I would like to plot structures onto a map, according to their coordinates. In my dataset, I have lat and long coordinates, but I also have the structure's ID (id) and the ID of the structure that leads into structure under observation (id_conn).

I would also like to have a line between "related" points. For example: the observation with id 0 would just be a dot. But the observation with id 101 has id_conn 0, and thus I would like there to be a line between structures 0 and 101.

Below I have some example code where I just plot the structures, without the lines, of course. I apologize if I'm also supposed to provide my Static Maps API key here - I think those are individual-specific though. One can see from the example dataset that the network that is created sometimes resets to a previous ID, so that id_conn is not always the id found in the previous observation. If anyone could provide insight here, I would appreciate it.

install.packages("ggmap")
library(ggmap)

register_google(##your Static Maps API key##,
                account_type = "standard")

Gmap <- get_map(location = c(lon = 0, lat = 0), zoom = 9)

aux <- data.frame(
  id = c(0, 101, 102, 103, 104, 105, 106, 201, 202, 203, 204, 205),
  lat_coord = c(0, 0.1, 0.2, 0.3, 0.3, 0.4, 0.5, 0, 0, 0.1, 0, -0.1),
  lon_coord = c(0, 0.1, 0.2, 0.2, 0.3, 0.2, 0.2, 0.2, 0.3, 0.4, 0.4, 0.4),
  id_conn = c(NA, 0, 101, 102, 102, 103, 105, 101, 201, 202, 202, 202)
)

ggmap(Gmap) +
  geom_point(data=aux, aes(x=lon_coord, y=lat_coord)) +
  theme_void() +
  theme(legend.key = element_rect(fill = "black")) +
  coord_equal(ratio=1)

Are you looking for something like this?

aux %>%
  inner_join(aux, by = c("id_conn" = "id")) %>%
  select(-id_conn.y) -> aux2


ggmap(Gmap) +
  geom_segment(data = aux2, aes(x = lon_coord.x, y = lat_coord.x, 
                                xend = lon_coord.y, yend = lat_coord.y), 
               color = "yellow", arrow = arrow(length = unit(0.2,"cm"))) +
  geom_point(aes(x=lon_coord.x, y=lat_coord.x),data=aux2) +
  geom_text(aes(x=lon_coord.x, y=lat_coord.x, label = id), data=aux2, hjust = -0.5) 

The secret ingredient is geom_segment() which allows you to add line segments. You can adjust the appearance of the arrows as you like.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM