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

Shiny应用中输出内修改数据集及桑基图渲染问题求助

问题解决指南

一、renderPlot无输出的原因及修正

你的代码存在语法、逻辑和图层调用的错误,导致图表无法生成:

  • 语法漏洞:ggplot的aes参数中缺少逗号,next_x = next_x后未加逗号,node = node前也缺失逗号;且geom_alluvial引用了未定义的bef.l.o对象,应改为处理后的bef.l。
  • if语句逻辑问题:判断条件的&需改为&&(逻辑与运算符),且if块多行代码必须加{},否则else会触发语法错误;另外UI中未添加input$x、input$y对应的控件(如复选框),导致输入值不存在,if条件永远无法触发。
  • 图层适配错误:ggsankey与ggplot配合时,更适合用geom_sankey系列图层,而非ggalluvial的geom_alluvial(两者语法规则不同)。

修正后的完整代码示例:

library(shiny)
library(ggsankey)
library(ggplot2)
library(dplyr)
library(readxl)

server <- function(input, output, session){
  output$Sankey <- renderPlot({
    # 修正if语句的语法与逻辑
    if(input$x && input$y) {
      bef <- read_excel("data1.xlsx")
    } else {
      bef <- read_excel("data2.xlsx")
    }
    
    # 用ggsankey的make_long处理数据
    bef.l <- bef %>% 
      make_long(col1, col2, value = col3)
    
    # 适配ggsankey的绘图语法
    ggplot(bef.l, aes(x = x, next_x = next_x, 
                      node = node, next_node = next_node,
                      fill = factor(node), value = value)) +
      geom_sankey(flow.alpha = 0.5, node.color = "black") +
      geom_sankey_label(size = 3, color = "white", fill = "gray40") +
      theme_sankey(base_size = 12)
  })
}

ui <- fluidPage(
  # 添加对应输入控件,确保input$x、input$y可被读取
  checkboxInput("x", "选择条件X"),
  checkboxInput("y", "选择条件Y"),
  plotOutput("Sankey")
)

shinyApp(ui, server)

二、reactive函数报错的原因及修正

你遇到的object of type 'closure' is not subsettable错误,由以下问题导致:

  • 直接使用x、y、z,需改为input$x、input$y、input$z(Shiny输入必须通过input对象获取);
  • 文件名后缀错误:data1.xslx应改为data1.xlsx;
  • if语句未加{},导致赋值逻辑混乱;
  • reactive函数可直接返回变量,无需额外使用return(虽不报错,但可简化)。

修正后的reactive代码示例:

datatable <- reactive({
  if (input$x && input$y && input$z) {
    bef <- read_excel("data1.xlsx")
  } else {
    bef <- read_excel("data2.xlsx")
  }
  bef
})

# 在renderPlot中调用reactive数据时必须加()
output$Sankey <- renderPlot({
  bef <- datatable()
  bef.l <- bef %>% make_long(col1, col2, value = col3)
  # 后续绘图代码同上述修正示例
})

额外注意事项

  • 确保Excel文件放在Shiny应用的工作目录下,或使用完整文件路径读取;
  • 检查Excel数据格式:col1、col2需为节点列,col3为流量值列,符合make_long的参数要求;
  • 若坚持使用ggalluvial的geom_alluvial,需注意其要求的数据格式为宽格式或alluvial专用格式,需调整映射参数适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:31:12