May*_*ans 5 r shiny shiny-reactivity
我正在尝试创建一个闪亮的应用程序,用户可以选择要绘制的 x 和 y 轴,然后单击“添加图形”以绘制图形 - 但此代码不起作用,我不确定为什么。我需要将input$x_iris和设置input$y_iris为反应式吗?
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel("4 Plot Generator"),
sidebarLayout(
sidebarPanel(
fluidRow(
column(6, selectInput("x_iris", "X:", choices= c(unique(colnames(iris))))),
column(6, selectInput("y_iris", "Y:", choices = c(unique(colnames(iris)))))
),
# button to add graph
# button to remove graph
fluidRow(
column(6, actionButton("add_graph", "Add Graph")),
column(6, actionButton("reset_graph", "Reset Graphs"))
)
),
# Show graph
mainPanel(
plotOutput("plots")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
observeEvent(input$add_graph,{
# not sure why this isn't working
plot1 <- ggplot(iris, aes(x = input$x_iris, y = input$y_iris)) + geom_point()
output$plots <- renderPlot({
plot1
})
})
observeEvent(input$reset_graph,{
plot1 <- NULL
output$plots <- renderPlot({
plot1
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
问题是selectInput小部件正在返回character值,但aes()并不期望如此。因此,要告诉它正确评估输入值,您可以使用aes_()和的组合as.name():
ggplot(iris, aes_(x = as.name(input$x_iris), y = as.name(input$y_iris)))
Run Code Online (Sandbox Code Playgroud)