You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RShiny交互式绘图应用选图表及坐标轴后未按预期运行求助

问题修复方案

你的代码运行不出预期效果,核心是几个硬伤,逐个改完就能正常运行:

  • ggplot的aes映射不支持直接传入input$xaxis这类字符串格式的列名,必须用.data代词做标准计算,否则图层找不到对应列
  • 图表分支逻辑残缺:目前只写了散点图、条形图两个分支,条形图分支还错用了散点图的geom_point,剩下的直方图、饼图、箱线图完全没有对应逻辑,选到这三类时绘图函数返回空值
  • UI代码有错误赋值:mainPanel里写的ui <- DT::dataTableOutput("charttable")是无效代码,多余的赋值操作会干扰UI渲染,而且你没有写对应的数据表渲染逻辑
  • 控件逻辑不匹配:直方图只需要X轴单变量,你固定展示Y轴选择器不符合图表使用逻辑
  • 你加的View selection按钮没有绑定任何触发逻辑,等于摆设

修改后完整可运行代码

# 先加载依赖包,未安装请先运行 install.packages(c("shiny","ggplot2","shinyWidgets","DT"))
library(shiny)
library(ggplot2)
library(shinyWidgets)
library(DT)

# 提前加载你的keep_df数据框,测试时可替换为mtcars等内置数据集验证
# keep_df <- your_own_dataframe

ui <- navbarPage("Title",
  tabPanel("Chart builder", 
    sidebarLayout(
      sidebarPanel(
        pickerInput(
          inputId = 'chart', 
          label = '1. Select chart type', 
          choices = c("Scatter plot", "Bar chart", "Histogram", "Pie chart", "Box plot"), 
          selected = "Scatter plot", 
          multiple = FALSE
        ),
        pickerInput(
          inputId = 'xaxis', 
          label = '2. Select X-axis', 
          choices = colnames(keep_df), 
          selected = colnames(keep_df)[1], 
          multiple = FALSE
        ),
        # 选直方图时自动隐藏Y轴选择器
        conditionalPanel(
          condition = "input.chart != 'Histogram'",
          pickerInput(
            inputId = 'yaxis', 
            label = '3. Select Y-axis', 
            choices = colnames(keep_df), 
            selected = colnames(keep_df)[2], 
            multiple = FALSE
          )
        ),
        actionButton("view", "View selection")
      ),
      mainPanel(
        DT::dataTableOutput("charttable"),
        plotOutput("plots", height = "600px")
      )
    )
  )
)


server <- function(input, output, session) {
  # 绑定查看按钮,点击后才重绘,避免选参数时反复刷新
  plot_obj <- eventReactive(input$view, {
    p <- ggplot(keep_df)
    switch(input$chart,
      "Scatter plot" = p + 
        geom_point(aes(x = .data[[input$xaxis]], y = .data[[input$yaxis]]), colour = "black"),
      "Bar chart" = p + 
        geom_col(aes(x = .data[[input$xaxis]], y = .data[[input$yaxis]]), fill = "steelblue"),
      "Histogram" = p + 
        geom_histogram(aes(x = .data[[input$xaxis]]), bins = 30, fill = "steelblue", colour = "white"),
      "Box plot" = p + 
        geom_boxplot(aes(x = .data[[input$xaxis]], y = .data[[input$yaxis]]), fill = "gray90"),
      "Pie chart" = {
        # 饼图默认对X轴分类列做计数统计,需要按Y轴汇总可自行修改统计逻辑
        agg_data <- as.data.frame(table(keep_df[[input$xaxis]]))
        names(agg_data) <- c("category", "value")
        ggplot(agg_data, aes(x = "", y = value, fill = category)) +
          geom_col() +
          coord_polar("y", start = 0) +
          theme_void()
      }
    )
  })
  
  output$plots <- renderPlot({
    plot_obj()
  })
  
  # 渲染选中列的数据预览表
  output$charttable <- renderDT({
    req(input$xaxis)
    select_cols <- if(input$chart == "Histogram") input$xaxis else c(input$xaxis, input$yaxis)
    keep_df[, select_cols, drop = FALSE]
  })
}

shinyApp(ui, server)

补充说明

  • 如果你不需要选完参数点按钮才出图,想要选完自动刷新,把eventReactive替换成普通的reactive即可
  • 条形图目前用geom_col实现,是直接展示Y轴对应数值;如果你需要做X轴分类计数,把geom_col换成geom_bar即可
  • 饼图的统计逻辑可以根据自己的需求调整,目前默认是统计X轴每个类别的出现次数

内容的提问来源于stack exchange,提问作者dataguy2650

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:18:25