1

I'm working on a project in which I have produced a choropleth map using plot_geo() from plotly in R. I am able to produce the choropleth map that I want when I create an map by directly passing in the z argument both in my app.R file and through the console. However, when I attempt to change the z argument to the user input from the UI, the map is does not get filled with the selected variable. My code is below.

library(tidyverse)
library(plotly)

data2 <- read.csv("tickets.csv") %>% 
  select(QUARTER, 
         ORIGIN, 
         ORIGIN_STATE_ABR, 
         ORIGIN_STATE_NM, 
         PASSENGERS,
         ITIN_FARE, 
         MILES_FLOWN,
         CARRIER_NAME)

data2 <- data2 %>% 
  filter(ORIGIN_STATE_ABR != "TT", ORIGIN_STATE_ABR != "PR") %>% 
  group_by(ORIGIN_STATE_ABR) %>% 
  summarise(median_itinerary_fare=median(ITIN_FARE),
            max_itinerary_fare=max(ITIN_FARE),
            median_miles_flown=median(MILES_FLOWN),
            max_miles_flown=max(MILES_FLOWN),
            mean_passengers=mean(PASSENGERS),
            total_passengers=sum(PASSENGERS))

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa')
)

summary_page <- tabPanel(
  "Summary"
)

map_page <- tabPanel(
  "Map Visualization",
  sidebarLayout(
    sidebarPanel(
      radioButtons(
        inputId = "level",
        label = "Select a Specificity Level: ",
        choices = list("State" = 1, "Airport" = 2),
        selected = 1
      ),
      selectInput(
        inputId = "agg_data",
        label = "Select an Aggregated Variable: ",
        choices = colnames(data2)[2:7],
        selected = "median_itin_fare"
      )
    ),
    mainPanel(
      plotlyOutput("state_map")
    )
  )
)

ui <- navbarPage(
  "Testing Plotly",
  summary_page,
  map_page
)

server <- function(input, output, session) {
  
  output$state_map <- renderPlotly({
    state_plot <- plot_geo(data = data2) %>%
      add_trace(locations = ~ORIGIN_STATE_ABR,
                z = ~input$agg_data,
                locationmode = 'USA-states',
                colors = 'Blues') %>%
      layout(geo = g,
             title = "Median Itinerary Fare Across All States")
  })
}

shinyApp(ui, server)

I have tried using reactive statements, but I am unfamiliar with them, and they don't appear to change anything. The map I'm trying to reproduce for each variable looks like this: Example Map for median_itinerary_fare Across USA

  • 1
    Try with `z = as.formula(paste0("~", input$agg_data))`. For other options see [How to make a plotly chart of variables selected by a user in shiny or flexdahsboard?](https://stackoverflow.com/questions/63543144/how-to-make-a-plotly-chart-of-variables-selected-by-a-user-in-shiny-or-flexdahsb) – stefan Dec 03 '21 at 00:36
  • 1
    That worked. Thank you @stefan – Dan Luettgen Dec 03 '21 at 01:24

0 Answers0