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

Shiny中响应式geom_boxplot绘图报错的解决方法求助

Shiny中响应式geom_boxplot绘图报错的解决方法求助

我最近在做一个简单的Shiny应用,想实现一个可以交互调整的箱线图,用ggplot来绘制。原本的需求是:初始显示所有分组的箱线图,按照所选变量的均值升序排列,默认选中第一个变量。

下面是我用来复现问题的示例代码(用类似的模拟数据):

library(tidyverse)
library(shiny)

## sample data ----
sample_df <- data.frame(
  var_1 = sample(1:20, 100, replace = TRUE),
  var_2 = sample(5:25, 100, replace = TRUE),
  var_3 = sample(1:15, 100, replace = TRUE),
  var_4 = sample(25:40, 100, replace = TRUE),
  group_name = rep(c('A', 'B', 'C', 'D'), 25)
)

## defined ui layout ----
ui <- fluidPage(titlePanel("Title"),
                sidebarLayout(
                  sidebarPanel(
                    checkboxGroupInput('group_choice', 'Choose Group', 
                                      choices = list('Group A' = 'A',
                                                     'Group B' = 'B',
                                                     'Group C' = 'C',
                                                     'Group D' = 'D'),
                                      selected = c('A', 'B', 'C', 'D')),
                    radioButtons('variable_choice', 'Variable for Boxplot', 
                                 choiceNames = c('var_1', 'var_2', 'var_3', 'var_4'),
                                 inline = TRUE, 
                                 choiceValues = c('var_1', 'var_2', 'var_3', 'var_4'), 
                                 selected = 'var_1')
                  ),
                  mainPanel(
                    tabsetPanel(type = 'tabs',
                                tabPanel('Explore Variables', plotOutput('variable_boxplot')))
                  )
                )
)

# Defined server logic ----
server <- function(input, output) {
  output$variable_boxplot <- renderPlot({
    sample_sub <- sample_df %>% 
      dplyr::select(c(group_name, input$variable_choice)) %>% 
      filter(group_name %in% input$group_choice)
    
    ggplot(sample_sub, aes(reorder(group_name, input$variable_choice), input$variable_choice, color = group_name)) +
      geom_boxplot() + geom_jitter(width = 0.2) +
      theme(legend.position = 'none') + labs(x = 'Group Name', y = 'Variable')
  })
}

shinyApp(ui, server)

运行这段代码后,我遇到了以下错误和警告:

Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future version of jsonlite, this option will not be supported, and named vectors will be translated into arrays instead of objects. If you want JSON object output, please use a named list instead. See ?toJSON.

Warning: Error in geom_boxplot: Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in tapply():
! arguments must have same length

我在Shiny环境外单独写代码绘制这个图是正常的,但放到Shiny的框架里就出现了问题,有没有人能帮我看看该怎么修复这个问题呀?

备注:内容来源于stack exchange,提问作者user21305404

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 12:09:06