2017-09-02 106 views
0

我是Shiny新手,學習它的功能。使用mtcars數據,我試圖創建一個圖表,其軸將根據用戶輸入而改變。當我運行該應用程序時,出現錯誤,告訴我「x和y長度不一樣」,因此看起來plot函數中指定的「data」沒有接收mtcars數據幀列。如果我將「數據」替換爲服務器功能中列出的任何列,那麼該圖將起作用。如何通過用戶輸入改變繪圖軸(閃亮)

shinyUI(navbarPage("My Application", 
    tabPanel("Component 1"), 
    tabPanel("Component 2"), 
    tabPanel("Component 3", 
    fluidPage(      
     fluidRow(  
     column(4, 
      "Sidebar", 
      helpText("This is my longer help text help text."), 
      selectInput("var", 
      label = "Choose a variable to display", 
      choices = c("mpg", "disp", "hp", "qsec"), 
      selected = "A") 
     ), 
     column(8, 
      #style = "background-color:#4d3a7d;", 
      "Main", 
      textOutput("selected_var"), 
      plotOutput("plot1") 
     ) 
    ) 
    ) 
), 
    navbarMenu("More", 
    tabPanel("Sub-Component A"), 
    tabPanel("Sub-Component B")) 
)) 


shinyServer(function(input, output) { 

    data <- reactive({ 
    if("mpg" %in% input$var) return(mtcars$mpg) 
    if("disp" %in% input$var) return(mtcars$disp) 
    if("hp" %in% input$var) return(mtcars$hp) 
    if("qsec" %in% input$var) return(mtcars$qsec) 
    }) 

    output$selected_var <- renderText({ 
    paste("you have selected", input$var) 
    }) 

    output$plot1 <- renderPlot({ 
    plot(mtcars$wt, data) 
    }) 
}) 

回答

0

我想通了 - 「數據」應該是「data()」。

0

我們也可以用switch代替if。另外,在selectInputselected中,它可能是choices之一。不知道在哪裏"A"定義

library(shiny) 

-ui

ui <- navbarPage("My Application", 
        tabPanel("Component 1"), 
        tabPanel("Component 2"), 
        tabPanel("Component 3", 
          fluidPage(      
           fluidRow(  
           column(4, 
             "Sidebar", 
             helpText("This is my longer help text help text."), 
             selectInput("var", 
                label = "Choose a variable to display", 
                choices = c("mpg", "disp", "hp", "qsec"), 
                selected = "mpg") 
           ), 
           column(8, 
             #style = "background-color:#4d3a7d;", 
             "Main", 
             textOutput("selected_var"), 
             plotOutput("plot1") 
           ) 
          ) 
          ) 
        ), 
        navbarMenu("More", 
           tabPanel("Sub-Component A"), 
           tabPanel("Sub-Component B")) 
) 

-server

server <- function(input, output) { 

    data <- reactive({ 
    switch(input$var, 
      mpg = mtcars$mpg, 
      dist = mtcars$disp, 
      hp = mtcars$hp, 
      qsec = mtcars$qsec 
      ) 

    }) 

    output$selected_var <- renderText({ 
    paste("you have selected", input$var) 
    }) 

    output$plot1 <- renderPlot({ 
    plot(mtcars$wt, data(), xlab = "wt", ylab = input$var) 
    }) 
} 
shinyApp(ui = ui, server = server) 

- 輸出

enter image description here

+0

這是偉大的,謝謝! –

+0

@ Josh.D謝謝你的評論。你也可以勾選[here](https://stackoverflow.com/help/someone-answers) – akrun