Flow map(Travel Path) Using Lat and Long in R

前端 未结 5 1735
臣服心动
臣服心动 2021-01-19 07:55

I am trying to plot flow map (for singapore) . I have Entry(Lat,Long) and Exit (Lat,long). I am trying to map the flow from entry to exit in singapore map.

s         


        
5条回答
  •  不思量自难忘°
    2021-01-19 08:49

    I would like to leave an alternative approach for you. What you can do is to restructure your data. Right now you have two columns for entry stations and the other two for exit stations. You can create one column for long, and another for lat by combing these columns. The trick is to use rbind() and c().

    Let's have a look of this simple example.

    x <- c(1, 3, 5)
    y <- c(2, 4, 6)
    c(rbind(x, y))
    
    #[1] 1 2 3 4 5 6
    

    Imagine x is long for entry stations and y for exit stations. 1 is longitude for a starting point. 2 is longitude where the first journey ended. As far as I can see from your sample data, it seems that 3 is identical 2. You could remove duplicated data points for each token_id. If you have a large set of data, perhaps this is something you want to consider. Back to the main point, you can create a column with longitude in the sequence you want with the combination of the two functions. Since you said you have date information, make sure you order the data by date. Then, the sequence of each journey appears in the right way in tmp. You want to do this with latitude as well.

    Now we look into your sample data. It seems that Exit_Station_Lat and Exit_Station_Long are in factor. The first operation is to convert them to numeric. Then, you apply the method above and create a data frame. I called your data mydf.

    library(dplyr)
    library(ggplot2)
    library(ggalt)
    library(ggthemes)
    library(raster)
    
    mydf %>%
    mutate_at(vars(Exit_Station_Lat: Exit_Station_Long),
              funs(as.numeric(as.character(.)))) -> mydf
    
    group_by(mydf, token_id) %>%
    do(data.frame(long = c(rbind(.$Entry_Station_Long,.$Exit_Station_Long)),
                  lat = c(rbind(.$Entry_Station_Lat, .$Exit_Station_Lat))
                 )
       ) -> tmp
    

    Now let's get a map data from GADM. You can download data using the raster package.

    getData(name = "GADM", country = "singapore", level = 0) %>%
    fortify -> singapore
    

    Finally, you draw a map. The key thing is to use group in aes in geom_path(). I hope this will let you move forward.

    ggplot() +
    geom_cartogram(data = singapore,
                   aes(x = long, y = lat, map_id = id),
                   map = singapore) +
    geom_path(data = tmp,
              aes(x = long, y = lat, group = token_id,
              color = as.character(token_id)),
              show.legend = FALSE) +
    theme_map() 
    

提交回复
热议问题