R中使用闪亮的多列旭日图

sunburst chart for multi columns in R using shiny

考虑以下数据

 > temp
   year  v13 per_v10 per_v11 per_v12
 1 1397 2506   20.11   65.13   14.76
 2 1398 1759   16.66   79.99    3.35
 3 1399 1754   19.44   75.43    5.13

 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")

我想在三年内为 4 个变量 (per_v10 ,per_v11 ,per_v12 ,per_v13) 制作饼图(1397,1398,1399) .它应该是这样的:

在每年的 Onclick 中 (1397:1399),它只显示那一年的百分比。 我看到了,但是太复杂了我看不懂

 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")
 
# create a df
(df <- data.frame(
     ids = c("total", paste0("total - ", temp$year), paste0("total - ", rep(temp$year, each = 3), " - ", rep(c('per_v10', 'per_v11', 'per_v12'), 3))),
     labels = c("Total", as.character(temp$year), rep(c('per_v10', 'per_v11', 'per_v12'), 3)),
     parents = c("", "total", "total", "total", rep(paste0("total - ", temp$year), each =3)),
     values = c(rep(0, 4), c(t(temp[, 3:5])))
 ))

library(plotly)
library(shiny)
library(shiny)
 
 ui <- fluidPage(
   plotlyOutput("myplot"),
   textOutput("percent")
 )
 
 server <- function(input, output, session) {
   output$myplot <- renderPlotly({
       plot_ly(
           data = df,
           ids = ~ids,
           labels = ~labels,
           parents = ~parents,
           type = 'sunburst',
           values = ~values,
           source = "myplot_source"
       )
   })
   output$percent <- renderPrint({
        clicked <- event_data(event = "plotly_click", source = "myplot_source", priority = "event")$pointNumber + 1
        req(clicked)
        if (clicked < 5) "You are not clicking on the children"
        else paste0("Clicked percentage is ", df$values[clicked])    
   })
 }
 
shinyApp(ui, server)

我根据你提供的百分比值画出了最外层的宽度。如果您希望每个箱子均匀分布,请删除行 values = ~values,

不确定 Onclick in each year 是什么意思。所以我把它变成了你提供的link。当您单击垃圾箱时,下方的文本栏将显示单击垃圾箱的百分比。

在 R 中绘制 sunburst 很烦人,您需要重新格式化数据框。我建议你试试 Python APIs.