[英]How do you use the reactive input as one of the axis of a plot in Shiny
我在使用 input$measurement 作为 y 轴时遇到问题,因此我无法更改显示的数据。
到目前为止,这是我的代码
library(dplyr)
library(ggplot2)
library(shiny)
library(shinyWidgets)
mtcars$cars <- rownames(mtcars)
c <- colnames(mtcars)
ui <- fluidPage(
titlePanel("Car comparisons"),
selectInput("measurement", "Select Measurement", choices = c, selected = "mpg"),
selectInput("car", "Select Car", choices = mtcars$cars, multiple=TRUE),
plotOutput("plot")
)
server <- function(input, output, session) {
data <- reactive({
mtcars %>%
filter(
input$measurement %in% c,
mtcars$cars %in% input$car
)
})
output$plot <- renderPlot({
req(input$measurement, input$car)
data() %>% lapply(input$measurement,
function(x) ggplot(aes(mtcars[,x])) +
geom_bar(stat="identity", fill="pink"))
})
}
shinyApp(ui = ui, server = server)`
当我将当前的 ggplot 更改为 ggplot(aes(y=mpg, x=cars)) 时它会起作用,但我希望能够更改显示的值。
你不需要在这里使用lapply
,你可以将input$measurement
变量放在aes
中,但需要将它包装起来以将其转换为表达式(或使用已弃用的aes_string
):
server <- function(input, output, session) {
data <- reactive({
mtcars %>%
filter(
input$measurement %in% c,
mtcars$cars %in% input$car
)
})
output$plot <- renderPlot({
req(input$measurement, input$car)
data() %>% ggplot(aes(cars, !!rlang::parse_expr(input$measurement))) +
geom_bar(stat="identity", fill="pink")
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.