rspatialmapdeck

Editing MapDeck Legend to Show Miles Instead of Meters


I am using MapDeck to use the mb_isochrone function to draw distances from a specific location in Arlington Heights, Illinois.

This is my code so far:

arlington.race <- c("-88.010102466048", "42.093383772976495")

isochrones <- mb_isochrone(arlington.race, 
                           distance = c(8046,
                                        16093,
                                        24140,
                                        32186))

mapdeck(style = mapdeck_style("streets"),
        location = c("-88.010102466048", "42.093383772976495"),
        zoom = 8.5) %>%
  add_polygon(data = isochrones,
              fill_colour = "distance",
              fill_opacity = 0.5,
              legend = TRUE,
              update_view = FALSE,
              legend_format = c(5, 10, 15, 20))

meters2miles <- c(5,10,15,20)

As you can see at the bottom, I am trying to use the legend_format function to edit the legend to show the distances in miles (5 miles, 10 miles, 15 miles, 20 miles). As well, I have tried to do it multiple ways including doing:

legend_format = list(meters2miles)

However, I cannot get the legend to switch from showing meters to miles no matter my method/attempt.


Solution

  • The legend_format argument expects a function to apply to the legend values

    Here's a reproducible example of how to use it

    library(mapdeck)
    set_token(secret::get_secret("MAPBOX"))  ## add your own API key
    
    df <- mapdeck::capitals
    
    ## colour the data by the 'value' column
    df$value <- sample(1:10, size = nrow(df), replace = T)
    
    ## in the legend we want to show the values multiplied by 1000
    legend_converter <- function(x) {
        return( as.numeric( x ) * 1000 )
    }
    
    mapdeck() %>%
        add_scatterplot(
            data = df
            , fill_colour = "value"
            , legend = TRUE
            , legend_format = list( fill_colour = legend_converter )
        )
    

    enter image description here


    Reference

    Here's the article I wrote on how to manipulate the legend