R Shiny dashboard通过select box选择散点图xy轴的实现与报错排查
问题排查结论
你的colnames(mtcars)使用没有错误,报错由服务端的两处语法问题导致:
- Shiny中
plotOutput对应的输出逻辑必须包裹在renderPlot()函数内,直接给output$scatter赋值ggplot对象不符合Shiny的输出绑定规则 input$scat_x、input$scat_y返回的是字符串格式的列名,直接传入aes()会被识别为常量字符串,不会映射到mtcars的对应列,需要用.data代词实现动态列映射
修正后完整代码
library(shiny) library(shinydashboard) library(ggplot2) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( fluidRow( box(selectInput("scat_x", label = h2("select x-axis"), choices = colnames(mtcars)), selectInput("scat_y", label = h2("select y-axis"), choices = colnames(mtcars))), box(plotOutput("scatter", height = 250)) ) ) ) server <- function(input, output) { output$scatter <- renderPlot({ ggplot(mtcars, aes(x = .data[[input$scat_x]], y = .data[[input$scat_y]])) + geom_point() }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

