Leaflet colours for polylines

前端 未结 2 1732
悲&欢浪女
悲&欢浪女 2020-12-18 12:30

I would like to use a basic data.frame to get three polylines each of different colours

I am currently using the below code as an example.

require(le         


        
相关标签:
2条回答
  • 2020-12-18 12:38

    Here is a way to automate for each group in your dataset:

    map <-  leaflet(df)
    map <- addTiles(map)
    for( group in levels(df$group)){
            map <- addPolylines(map, lng=~lon,lat=~lat,data=df[df$group==group,], color=~col)
            }
    map
    
    0 讨论(0)
  • 2020-12-18 12:48

    Have a look at mapview which is based on leaflet (at least for small datasets) and has been designed for such particular tasks. The fundamental difference is that you are required to convert df to an object of class SpatialLines* before you can pass the data on to mapview. Here is a short code snippet based on your sample data.

    ## load packages
    library(sp)
    library(mapview)
    
    ## sample data
    set.seed(10)
    df <- data.frame(lat = c(rnorm(20, 50), rnorm(40, 0), rnorm(40, -30)),
                     lon = rnorm(100),
                     group = rep(letters[1:3], times = c(20, 40, 40)),
                     col = rep(rainbow(3, alpha = NULL), times = c(20, 40, 40)), 
                     stringsAsFactors = FALSE)
    
    ## 'Lines' list
    lst_lns <- lapply(letters[1:3], function(i) {
      df_sub <- subset(df, group == i)
      ln <- Line(df_sub[, 2:1])
      Lines(list(ln), ID = i)
    })
    
    ## to 'SpatialLines'
    sln <- SpatialLines(lst_lns, proj4string = CRS("+init=epsg:4326"))
    
    ## to 'SpatialLinesDataFrame'
    slndf <- SpatialLinesDataFrame(sln, match.ID = FALSE, 
                                   data = unique(df[, c("group", "col")]))
    
    ## display data
    mapview(slndf, zcol = "group", color = slndf@data$col)
    

    0 讨论(0)
提交回复
热议问题