问题
I am trying to connect one location on the map of the US with multiple locations on the map of the US.
library(tidyverse)
library(flights13)
First, I am selecting all flights from Newark airport (EWR) on January 1, 2013 and grabbing the geographic coordinates for the destinations (if available in the tibble airports - and add EWR's location on top):
ewr <- flights %>%
filter(year== 2013, month== 1, day== 1, origin== "EWR") %>%
select(dest) %>%
distinct(dest) %>%
arrange(dest)
# Join it with airports database, add column "origin" filled with EWR:
mydest <- ewr %>%
left_join(select(airports, faa, lat, lon),
by = c("dest" = "faa")) %>%
filter(!is.na(lat)) %>%
select(lat, lon)
mydest
# Grab EWR coords:
ewrcoords <- airports %>%
filter(faa == "EWR") %>%
select(lat, lon)
ewrcoords
mydest <- rbind(ewrcoords, mydest)
Then, I want to connect the EWR (Newark) location with all the destination locations. I tried to do it using a loop, but it's not working inside ggplot
:
mydest %>%
ggplot(aes(lon, lat)) +
borders("state") +
geom_point() +
coord_quickmap() %>%
for(i in 2:nrow(mydest)) {
geom_line(data = mydest[c(1,i),], aes(lon, lat),
color = "black", size = 1)
}
Is it possible to do it without a loop? Or how could I make the loop work? Thank you very much!
回答1:
Try this:
colnames(ewrcoords) = c("EWRlat", "EWRlon")
mydest <- cbind(ewrcoords, mydest)
mydest %>%
ggplot(aes(lon, lat)) +
borders("state") +
geom_point() +
geom_segment(aes(y=EWRlat, x=EWRlon, xend=lon, yend=lat))+
coord_quickmap()
EDIT: sorry did not see it was already in the comment by eipi10.
来源:https://stackoverflow.com/questions/46158896/r-ggplot-connecting-one-point-on-a-map-with-multiple-points-on-the-same-map