You need to enable JavaScript to run this app. R Shiny dashboard通过select box选择散点图xy轴的实现与报错排查
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 23:57:03