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

在R中用plotly或highcharts实现webr式交互式嵌套环形图可行吗?

当然可以用plotly和highcharter包在R中绘制这种交互式嵌套环形图(即双层甜甜圈图),下面分别给出具体实现代码:

使用plotly实现交互式嵌套环形图

先加载依赖包并处理数据:

library(plotly)
library(dplyr)

# 处理泰坦尼克号数据集
data <- as.data.frame(Titanic)
pd <- data %>% 
  group_by(Class, Survived) %>% 
  summarise(n = sum(Freq), .groups = "drop")

通过双层饼图(设置hole参数实现环形)来构建嵌套效果:

# 统计外层舱室的总人数
outer_data <- pd %>% 
  group_by(Class) %>% 
  summarise(total = sum(n), .groups = "drop")

# 内层按舱室分组的存活数据
inner_data <- pd

# 绘制交互式图表
plot_ly() %>%
  # 添加外层环形(舱室维度)
  add_pie(data = outer_data, labels = ~Class, values = ~total,
          name = "舱室", hole = 0.5,
          textinfo = "label+percent", textposition = "outside") %>%
  # 添加内层环形(存活情况维度)
  add_pie(data = inner_data, labels = ~Survived, values = ~n,
          name = "存活情况", hole = 0.8,
          domain = list(x = c(0.1, 0.9), y = c(0.1, 0.9)),
          textinfo = "label+value", textposition = "inside") %>%
  # 布局设置
  layout(title = "Titanic: 不同舱室的存活情况",
         showlegend = TRUE,
         annotations = list(
           list(x = 0.5, y = 0.5, text = "嵌套环形图", showarrow = FALSE)
         ))

使用highcharter实现交互式嵌套环形图

加载依赖包并处理数据为highcharts适配的层级格式:

library(highcharter)
library(dplyr)

data <- as.data.frame(Titanic)
pd <- data %>% 
  group_by(Class, Survived) %>% 
  summarise(n = sum(Freq), .groups = "drop")

# 转换为highcharts需要的嵌套数据结构
hc_data <- pd %>%
  group_by(Class) %>%
  summarise(
    name = as.character(first(Class)),
    y = sum(n),
    data = list(pmap(list(Survived, n), function(label, val) {
      list(name = as.character(label), y = val)
    })),
    .groups = "drop"
  )

绘制交互式嵌套环形图:

highchart() %>%
  hc_chart(type = "pie") %>%
  hc_title(text = "Titanic: 不同舱室的存活情况") %>%
  hc_plotOptions(
    pie = list(
      innerSize = "50%", # 设置内层空心比例,实现环形
      allowPointSelect = TRUE,
      cursor = "pointer",
      dataLabels = list(
        enabled = TRUE,
        format = "<b>{point.name}</b>: {point.percentage:.1f}%"
      )
    )
  ) %>%
  hc_series(
    list(
      name = "舱室",
      data = list_parse(hc_data)
    )
  )

内容的提问来源于stack exchange,提问作者Lee Jim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:05:24