简体   繁体   中英

how to let user choose the x_var in Shiny plot?

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)

The problem is in the TD$x_var . I wanna refer to the variable selected from the selectInput but with this code I get "Erroe[object object]."

Inside the renderPlot , x_var() is already assigned to x . So, we call x instead of x_var . Also, to evaluate the object, we may use [[ instead of $

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))
  })
})

Or instead of extracting the column, use unquoted column names after specifying the data . This will also correctly name the legend

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))
  })
})

-using a reproducible example with iris

TD <- iris

ui <-shinyUI(fluidPage(pageWithSidebar(
  headerPanel("Test App"),
  sidebarPanel(
    selectInput("xaxis", "Choose a x variable", choices = names(TD)[1:4]),
    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()
    
    
    p <- ggplot(TD) +
      geom_bar(aes(.data[[x]], fill =Species))
    p
    
  })
})

shinyApp(ui,server)

-output

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM