Search code examples
rleafletr-leaflet

Different colors for flight routes leaflet with R


I am stuck with a problem with leaflet.
I want to plot flight routes (already done with gcIntermediate) but i want to colour the routes based on a factor variable (Status:cancelled,delayed).
I would want delayed routes colored with blue and the cancelled ones with red

my R code:

gcIntermediate(coord1[,c(1,2)], coord1[,c(3,4)],  
               n=100,   
               addStartEnd=TRUE,  
               sp=TRUE) %>%   
  leaflet() %>%   
  addTiles() %>%   
  setView(-100,38, zoom = 4.49) %>%   
  addPolylines(color="red") %>%   
  addMarkers(lng=c(coord1[,1],coord1[,3]),lat=c(coord1[,2],coord1[,4]))

where coord1 is a dataframe with: the latitudes and logitudes of two cities and the factor variable(status).


Solution

  •         coord1 <- data.frame("Longitud1" = c(-84.42694,-82.42694,-104.66700),   
      "Latitud1"=c(33.64044,33.64044,39.85841), 
     "Longitud2"=c(-97.03720,-80.15275,-112.00806), 
         "Latitud2"=c(32.89595,26.07258,33.43417), 
         "estado"=c("Delayed","Delayed","Cancelled")) 
    

    And the answer is:

    colores<-function(df){ color<-c() for( i in 1: nrow(coord1)){ if (df$estado[i]=="Cancelled") { color<-c(color,"red") }else{ color<-c(color,"orange") } } return(color) } 
    
     gcIntermediate(coord1[,c(1,2)], coord1[,c(3,4)], n=100, addStartEnd=TRUE, sp=TRUE) %>% leaflet() %>% addTiles() %>% setView(-100,38, zoom = 4.49) %>% addPolylines(color=colores(coord1)) %>% 
      addMarkers(lng=c(coord1[,1],coord1[,3]),lat=c(coord1[,2],coord1[,4]))