简体   繁体   English

将地图上的一个点与同一地图上的多个点连接的R ggplot

[英]R ggplot connecting one point on a map with multiple points on the same map

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): 首先,我选择了2013年1月1日从纽瓦克机场(EWR)出发的所有航班,并获取目的地的地理坐标(如果在小飞机场中可用-并在顶部添加EWR的位置):

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. 然后,我想将EWR(纽瓦克)位置与所有目标位置连接起来。 I tried to do it using a loop, but it's not working inside ggplot : 我尝试使用循环来做到这一点,但在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! 非常感谢你!

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. 编辑:对不起,没有看到它已经在eipi10的评论中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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