-->

Dynamic Color Fill For Polygon Using Leaflet In Sh

2020-05-02 02:16发布

问题:

My goal is to create a map that highlights states based on a dropdown menu. I have produced a map that works as intended for one of the metrics in the data set, but when I try and recreate the map in a shiny app the states are all grey rather than varying shades of green. Here is my code:

library(shiny)
library(tidyverse)
library(leaflet)
library(dplyr)
library(tigris)
library(DT)
library(rgdal)
library(RColorBrewer)


#create the UI
ui <- fluidPage(
  #create title
  titlePanel("Interactions by State"),
  sidebarLayout(
    sidebarPanel(

      selectInput("interactionMetric",
                  label = "Choose a Metric",
                  choices = c("Sentiment",
                              "Average Totals",
                              "Management Fee"),
                  selected = "Sentiment")
                ),
      mainPanel(
        leafletOutput("mymap"),
        p()
      )
  )
)


#Create the server

server <- function(input, output, session) {
  #get the data
  primaryDf <- read.csv('InteractionsFormattedFirstMonth.csv', header = TRUE, sep = ',')

  #select the input
  decision <- reactive({
      switch(input$interactionMetric,
                   "Sentiment" = primaryDf$Average.of.Average.Sentiment,
                   "Average Totals" = primaryDf$Average.of.Event.Value,
                   "Management Fee" = primaryDf$Average.of.MGT.Fee)
  })

  #create dataframe based on input
  newDf <- reactive({
    cbind(primaryDf["Row.Labels"],decision())
  })

  #create the states and join with dataframe to create spatial object
  statesUsed <- states(cb=T)
  states_merged <- reactive({
    geo_join(statesUsed, newDf(), "STUSPS", "Row.Labels", how = 'inner')
  })

  #create the function for a color pallette
  pal <- reactive({
    colorQuantile("YlGn", states_merged()$decision, n = 5)
  })

  #create the map to be rendered in the UI  
  output$mymap <- renderLeaflet({
      leaflet(data = states_merged()) %>% 
         addProviderTiles("CartoDB.Positron") %>%
         setView(-98.483330, 38.712046, zoom = 4) %>%
         addPolygons(data = states_merged(),
                      fillColor = ~pal(),
                      fillOpacity = 0.7,
                      weight = 0.2,
                      smoothFactor = 0.2
                      )
  })
}

shinyApp(ui, server)

For reference, here's what the data looks like:

> head(primaryDf)
  UniqueID Row.Labels Average.of.Event.Value Average.of.Average.Sentiment Average.of.MGT.Fee Sum.of.UniqueID
1        1         AL               4.000000                     3.000000           600.0000             311
2        2         AR               1.500000                     3.000000           600.0000              83
3        3         AZ               3.600000                     3.000000           560.0000             736
4        5         CA               4.567568                     3.138108           883.7838            4346
5        6         CO               3.000000                     3.167500           450.0000             389
6        7         CT               6.333333                     3.033333           500.0000             249

The code to this point results in a map of the US with all states included in the data set greyed out. As a fix, I tried this:

addPolygons(data = states_merged(),
                      fillColor = ~pal(states_merged()$decision),
                      fillOpacity = 0.7,
                      weight = 0.2,
                      smoothFactor = 0.2
                      )

However, this results in the error "unused argument (states_merged()$decision)" Thanks to whomever can help me figure this out, I've been struggling with it nonstop for a few days and it's driving me crazy!

回答1:

I found this reference: https://github.com/rstudio/shiny/issues/858

The solution is that pal() is a function, but the data to be passed to it has to go next to it for some reason. It's really odd, but here's what the working code looks like:

  output$mymap <- renderLeaflet({
      leaflet(data = states_merged()) %>% 
         addProviderTiles("CartoDB.Positron") %>%
         setView(-98.483330, 38.712046, zoom = 4) %>%
         addPolygons(data = states_merged(),
                      #note the solution here, "pal()(decision())
                      fillColor = ~pal()(decision()),
                      fillOpacity = 0.7,
                      weight = 0.2,
                      smoothFactor = 0.2
                      )
  })
}