Search code examples
rshinyr-leaflet

Changing legend title in a leaflet map in shiny


I have a list of possible coloring options in a map in shiny + leaflet, such as

vars <- c("Difference"  = "diff",
          "Index"       = "index",
          "City Cargo"  = "cid_carga",
          "City score"  = "carga_mun_score")

From the above variables I create a selection list, which will be used to select the desired variable to be colored in the map

selectInput("color", "Color", vars, selected = "carga_mun_score")

However, and obviously, when I create the legend title in the leaflet map, the title stays as the actual name of the variable, e.g., "cid_cargo" instead of "City Cargo".

addLegend("bottomleft",pal = pal, values = df[[input$color]], title = input$color,
                          layerId = "colorLegend")

enter image description here

Is there a way to use my alias (in the example above "city score") name instead of the actual variable name ("carga_mun_score"), without using a really long if clause?


Solution

  • Simply:

    addLegend("bottomleft",pal = pal, values = df[[input$color]], 
                              layerId = "colorLegend", title="City Score")
    

    Or save your selection to a variable that can translate the names:

    varname<-switch(input$color,
               "diff" = "Difference",
               "index"="Index",
              "cid_carga"="City Cargo",
              "carga_mun_score"="City score")
    

    Then pass that variable to your leaflet legend:

        addLegend("bottomleft",pal = pal, values = df[[input$color]],
                                  layerId = "colorLegend", title=varname)