首页 > 解决方案 > R Shiny 允许用户选择要显示的图

问题描述

我根据我的数据绘制了一些图,我使用 shiny 来绘制地图和图,让用户选择要显示的图,但我收到错误消息:

Warning: Error in <reactive:graphInput>: duplicate 'switch' default value:'"New South...'and'"Victoria"...'
  [No stack trace available] 

这是我的代码:

region_name <- c("New South Wales","Victoria","Queensland","South Australia","Western Australia","Tasmania",
                 "Northern Territory","Australian Capital Territory")

ui <- fluidPage(
  titlePanel("Agriculture"),
  tmapOutput("water_map"),
  selectInput("water_graph","Choose a region to graph:",
              choices = region_name),
  plotOutput("selected_water")
)

## xxx_water_plot is made by ggplot2, and it display correctly without shiny

server <- function(input,output,session){
  output$water_map <- renderTmap(water_map)
  nsw_water_show <- reactive(nsw_water_plot)
  vic_water_show <- reactive(vic_water_plot)
  qld_water_show <- reactive(qld_water_plot)
  sald_water_show <- reactive(sa_water_plot)
  wa_water_show <- reactive(wa_water_plot)
  tas_water_show <- reactive(tas_water_plot)
  nt_water_show <- reactive(nt_water_plot)
  act_water_show <- reactive(act_water_plot)
  graphInput <- reactive({
    switch(input$water_graph,
           "New South Wales" <- nsw_water_show(),
           "Victoria" <- vic_water_show(),
           "Queensland" <- qld_water_show(),
           "South Australia" <- sa_water_show(),
           "Western Australia" <- wa_water_show(),
           "Tasmania" <- tas_water_show(),
           "Northern Territory" <- nt_water_show(),
           "Australia Capital Territory" <- act_water_show()
           )
  })
  output$selected_water <- renderPlot({
    graphInput()
    
  })
}

我不知道问题出在哪里,tmap 显示正确,并且选择的位置与我想的一样,但是绘图没有显示出来。我不明白错误消息,选择中不应有任何重复值。谁能帮我?谢谢。

标签: rggplot2shiny

解决方案


在你的开关中用 = 而不是 <- 试试。

switch(input$water_graph,
           "New South Wales" = nsw_water_show(),
           "Victoria" = vic_water_show(),

等等

<- 是一个赋值运算符,因此它为前两个赋值然后找到一个默认值,而不是将每一行读取为一个开关元素。


推荐阅读