2017-09-02 67 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