未调用unique却触发unique.default错误:R Shiny树形图无法渲染
问题解决:Shiny应用树形图无法展示及
unique()错误修复 错误根源分析
虽然你没有直接调用unique(),但错误来自两个核心问题:
- 语法与参数不匹配:
parents < ""是赋值错误,且plotly树形图的parents参数需要与labels长度一致;同时你误用了ggplot2的scale_color_brewer作为plotly的color参数,plotly无法识别该对象,内部处理时触发unique()错误。 - selectizeInput性能警告:未规范指定
choices参数,且选项过多时未启用服务器端渲染。
修正后的完整代码
# Define UI ui <- fluidPage( # Use tags$head to include custom CSS styles tags$head( tags$title('2023 Pacific Data Visualisation entry'), tags$style(HTML(" body { background-color: #c9e8fc; font-family: Arial; } h1 { font-size: 16px; color: #032e9b; } ")) ), titlePanel("PACIFIC DATA VISUALISATION"), sidebarLayout( sidebarPanel( "Please pick the importer country(s) and year(s) you are interested in seeing information for", width = 4, # 规范指定choices参数,留空待服务器端更新 selectizeInput("importer", "Importer:", choices = NULL, multiple = FALSE), selectizeInput("year", "Year:", choices = NULL, multiple = FALSE) ), mainPanel( h4("Treemap of selected importer commodities"), plotlyOutput("treemap", width = "100%", height = "600px") ) ) ) # Define server logic for the Shiny app server <- function(session, input, output) { # 服务器端渲染selectizeInput,解决性能警告 observe({ updateSelectizeInput(session, "importer", choices = unique(data_pv$importer), server = TRUE) updateSelectizeInput(session, "year", choices = unique(data_pv$year), server = TRUE) }) output$treemap <- renderPlotly({ # Filter data based on selected year and importer filteredData <- data_pv %>% filter(year %in% input$year, importer %in% input$importer) %>% filter(obs_val > 0) # 处理空数据情况,避免报错 if(nrow(filteredData) == 0){ return(plot_ly() %>% layout(title = "No data available for selected filters")) } # 确保parents与labels长度一致 labels <- filteredData$commodity parents <- rep("", nrow(filteredData)) values <- filteredData$obs_val # 使用plotly支持的颜色方式:直接指定调色板名称,或生成颜色向量 treemap <- plot_ly( type='treemap', labels=labels, parents=parents, values=values, # 使用plotly内置的调色板,或自定义颜色向量 colors = "BrBG", textinfo="label+percent entry" ) treemap }) } shinyApp(ui, server)
关键修改说明
- 修复selectizeInput性能问题:在server中用
updateSelectizeInput设置server=TRUE,并提前用unique()去重选项,减少加载压力。 - 修正树形图参数错误:
- 将
parents < ""改为parents <- rep("", nrow(filteredData)),保证parents与labels长度完全匹配。 - 替换
scale_color_brewer为plotly支持的colors参数,直接指定调色板名称(如"BrBG"),或用RColorBrewer::brewer.pal()生成颜色向量。
- 将
- 增加空数据判断:避免筛选后无数据时触发额外错误,给出友好提示。
内容的提问来源于stack exchange,提问作者Russ
相关产品推荐
相关产品推荐

