[英]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
.问题出在TD$x_var
中。 I wanna refer to the variable selected from the selectInput but with this code I get "Erroe[object object]."我想引用从 selectInput 中选择的变量,但使用这段代码我得到“Erroe [object object]”。
Inside the renderPlot
, x_var()
is already assigned to x
.在renderPlot
内部, x_var()
已经分配给x
。 So, we call x
instead of x_var
.因此,我们调用x
而不是x_var
。 Also, to evaluate the object, we may use [[
instead of $
此外,为了评估 object,我们可以使用[[
而不是$
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
.或者不提取列,而是在指定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
-使用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 -输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.