I am new to Shiny and learning it's features. Using the mtcars data, I am trying to create a plot whose axis will alter upon user input. When I run the app, I am getting error telling me the "x and y lengths are not the same", so it appears that "data" specified in the plot function is not receiving the mtcars dataframe columns. The plot works property if I replace "data" with any of the columns listed in the server function.
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)
})
})
我想通了-“数据”应该是“ data()”。
We could also use switch
instead of if
. Also, in the selected
in selectInput
, it could be one of the choices
. Not sure where "A"
is defined
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)
-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.