问题
I am using Shiny's varSelectInput function to display a map with R Leaflet from spatialpolygondataframe, so that by selecting a variable of the object the map of the corresponding variable is drawn and I changed its color. For this I have generated a reactive object of the ColorBin function of R leaflet from conditional varSelectInput. All this when rendering the map works correctly and consequently the map is painted, updating the color and the title of the legend. However, when deploying the legend (addLegend) I do not have the expected result, since it is not displayed. I tried to pass the argument from a reactive object when the map is rendered just as I did with the addPolygons function, but I did not achieve the expected result. as shown in the following figure: enter image description here
43/5000 The code I have used is as follows:
library(shiny)
library(leaflet)
library(tidyverse)
ssd_map <- leaflet() %>% addProviderTiles("CartoDB.DarkMatter")%>% setView(-8.53, 42.90, zoom = 12)
ui <- fluidPage(
titlePanel("Santiago de Compostela"),
mainPanel(
varSelectInput(
inputId = "option",
label = "Elige la información a representar:",
data = dataframe1 %>% select(`Población Total`,`Población Masculina`,`Población Femenina`,`Población < 16 años`)
),
leafletOutput("map")
))
server <- function(input, output) {
colorpal <- reactive({
if(input$option == "Población Total") {
colorBin("Blues",data$`Población Total`,bins = 5)
} else if (input$option == "Población Masculina"){
colorBin("Reds",data$`Población Masculina`,bins = 5)
} else if (input$option == "Población Femenina"){
colorBin("Oranges",data$`Población Femenina`,bins = 5)
} else
colorBin("Greens",data$`Población < 16 años`,bins = 5)
})
leyenda <- reactive({
if(input$option == "Población Total") {
data$`Población Total`
} else if (input$option == "Población Masculina"){
data$`Población Masculina`
} else if (input$option == "Población Femenina"){
data$`Población Femenina`
} else
data$`Población < 16 años`
})
output$map <- renderLeaflet({
ssd_map
})
observe({
pal <- colorpal()
leg <- leyenda()
leafletProxy("map", data = dat1) %>%
clearShapes() %>%
clearControls() %>%
addPolygons(color = "#444444" ,
weight = 1,
smoothFactor = 0.5,
opacity = 1.0,
fillOpacity = 0.5,
popup = ~paste(input$option) ,
fillColor = ~pal(eval(as.symbol(input$option))))%>%
addLegend(position = "topright", pal = pal , values =leg[input$option] ,
title = ~paste(input$option))
})
}
shinyApp(ui = ui, server = server)
来源:https://stackoverflow.com/questions/60058905/addlegend-r-leaflet-based-on-user-input