【问题标题】:how to let user choose the x_var in Shiny plot?如何让用户在 Shiny plot 中选择 x_var?
【发布时间】:2023-01-08 04:22:17
【问题描述】:
TD <- thyroid

library(readxl)
library(shiny)
library(ggplot2)
library(shinythemes)
library(DT)

ui <-shinyUI(fluidPage(pageWithSidebar(
  headerPanel("Test App"),
  sidebarPanel(
    selectInput("xaxis", "Choose a x variable", choices = names(TD)),
    actionButton("goButton","Update")
  ),
  mainPanel(
    tabsetPanel(
      tabPanel('Plot', plotOutput("plot1"))
    ))
)
))

server <- shinyServer(function(input,output, session){

  x_var<- eventReactive(input$goButton, {
    input$xaxis
  })
  

  output$plot1 <- renderPlot({
    x <- x_var()
    x
    
    p <- ggplot() + geom_bar(aes(TD$x_var, fill = TD$ThryroidClass))
    p  #+ 
      #theme(plot.title = element_text(hjust = 0.5, size=20))
  })
})

shinyApp(ui,server)

问题出在TD$x_var。我想引用从 selectInput 中选择的变量 但是有了这段代码我得到 “Erroe [对象对象]。”

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    renderPlot 内部,x_var() 已分配给x。所以,我们调用x而不是x_var。此外,为了评估对象,我们可以使用 [[ 而不是 $

    output$plot1 <- renderPlot({
        x <- x_var()
        x
        
        p <- ggplot() +
          geom_bar(aes(TD[[x]], fill = TD$ThryroidClass))
        p  #+ 
          #theme(plot.title = element_text(hjust = 0.5, size=20))
      })
    })
    

    或者不提取列,而是在指定 data 后使用不带引号的列名。这也将正确命名图例

    output$plot1 <- renderPlot({
        x <- x_var()
        x
        
        p <- ggplot(TD) +
          geom_bar(aes(.data[[x]], fill =ThryroidClass))
        p  #+ 
          #theme(plot.title = element_text(hjust = 0.5, size=20))
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多