基于R Shiny的多列数据Sunburst Chart点击交互实现咨询
R Shiny 简易实现可下钻旭日图(Sunburst Chart)
实现思路
- 无需复杂的点击事件监听,直接利用Plotly旭日图原生的下钻交互能力,只要提前构造好符合要求的层级数据即可实现点击年份切片展示对应类别占比的效果
- 数据预处理环节将宽表转为旭日图要求的
labels/parents/values结构化格式 - 依赖包仅需
shiny、plotly、dplyr、tidyr四个常用包
完整可运行代码
# 加载依赖包 library(shiny) library(plotly) library(dplyr) library(tidyr) # 定义原始数据集 temp <- structure(list(year = c(1397, 1398, 1399), v13 = c(2506, 1759, 1754), per_v10 = c(20.11, 16.66, 19.44), per_v11 = c(65.13, 79.99, 75.43), per_v12 = c(14.76, 3.35, 5.13)), row.names = c(NA, -3L), class = "data.frame") # 构造旭日图层级数据 sunburst_data <- bind_rows( # 1. 根节点:全部年份 tibble( labels = "全部年份", ids = "total", parents = "", values = sum(temp$v13) ), # 2. 第二层:年份节点 temp %>% mutate( labels = as.character(year), ids = paste0("year_", year), parents = "total", values = v13 ) %>% select(labels, ids, parents, values), # 3. 第三层:各年份下的占比类别节点 temp %>% pivot_longer(cols = starts_with("per_"), names_to = "var", values_to = "per") %>% mutate( labels = var, ids = paste0("year_", year, "_", var), parents = paste0("year_", year), values = v13 * per / 100 # 转换为绝对值计算占比 ) %>% select(labels, ids, parents, values) ) # Shiny UI定义 ui <- fluidPage( plotlyOutput("sunburst_plot", height = "800px") ) # Shiny服务端定义 server <- function(input, output, session) { output$sunburst_plot <- renderPlotly({ plot_ly( data = sunburst_data, ids = ~ids, labels = ~labels, parents = ~parents, values = ~values, type = "sunburst", branchvalues = "total" ) %>% layout( sunburstcolorway = c("#636efa", "#ef553b", "#00cc96", "#ab63fa"), title = "年份-类别占比旭日图" ) }) } # 运行Shiny应用 shinyApp(ui, server)
效果说明
- 初始状态展示全部年份的整体占比,外层为三个年份的占比,内层为各年份下的per类别占比
- 点击任意年份切片,会自动下钻仅展示该年份下三个per变量的占比,点击中心区域即可返回上一级
- 如果需要新增
per_v13等更多变量,只需在原始数据中添加对应列,预处理逻辑会自动识别生成对应层级节点
内容的提问来源于stack exchange,提问作者Masoud
相关产品推荐
相关产品推荐

