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

R语言Plotly交互式Treemap空白及国家嵌套失败求助

解决Plotly Treemap空白及实现国家嵌套的问题

问题根源

你的代码中所有节点的parents都设为空字符串,且同一个国家对应多个segment条目,Plotly无法解析这种重复顶级节点的结构,导致图表空白。要实现国家嵌套segment的层级,需要构建清晰的父子节点关系:

  • 顶层节点:各个BRICS国家,对应该国的总排放量
  • 子节点:每个国家下的不同segment,对应各segment的排放量

修正步骤

  1. 重构数据结构:生成包含顶层国家节点和子级segment节点的数据集
  2. 调整Plotly参数:匹配新的数据层级,确保ids唯一、parents正确指向父节点

完整修正代码

library(tidyverse)
library(plotly)
library(RColorBrewer)

# URL of the dataset(s)
url_1 <- "https://api.iea.org/methane/comparison?source=IEA&csv=true"

# Read the data from the URL into a data frame called CH4
CH4 <- read_csv(url_1)

BRICS <- CH4 %>%
  filter(segment != "Total") %>%
  filter(country %in% c("Brazil", "Russia", "India", "China", "South Africa")) %>%
  select(country, segment, emissions) %>%
  mutate(emissions_rounded = signif(emissions, digits = 3))

# 1. 构建层级数据:先添加国家总排放量作为顶层节点
country_totals <- BRICS %>%
  group_by(country) %>%
  summarise(emissions_rounded = sum(emissions_rounded), .groups = "drop") %>%
  mutate(segment = country, parent = "")  # 顶层节点的父为空,segment字段暂存国家名

# 2. 处理子节点:每个segment的父节点是对应的国家
segment_nodes <- BRICS %>%
  mutate(parent = country)

# 3. 合并顶层和子节点数据
treemap_data <- bind_rows(country_totals, segment_nodes) %>%
  mutate(
    ids = ifelse(parent == "", segment, paste(country, segment, sep = "-")),  # 确保ids唯一
    labels = ifelse(parent == "", segment, segment)  # 顶层显示国家名,子层显示segment名
  )

# Create a color palette for the unique segments
unique_segments <- unique(BRICS$segment)
colors <- brewer.pal(length(unique_segments), "Set3")
color_map <- setNames(colors, unique_segments)
# 给顶层国家节点添加统一颜色(可选,这里用灰色)
color_map <- c(color_map, "Brazil" = "#cccccc", "Russia" = "#cccccc", "India" = "#cccccc", "China" = "#cccccc", "South Africa" = "#cccccc")

plot_ly(
  data = treemap_data,
  type = "treemap",
  ids = ~ids,
  labels = ~labels,
  parents = ~parent,
  values = ~emissions_rounded,
  hoverinfo = "text",
  hovertemplate = "<b>%{label}</b><br>排放量: %{value}<extra></extra>",
  textposition = "inside",
  insidetextanchor = "middle",
  textfont = list(size = 14),
  marker = list(
    colors = ~color_map[ifelse(parent == "", labels, segment)],
    colorscale = "identity",
    showscale = TRUE,
    colorbar = list(title = "Segment")
  )
) %>%
  layout(title = "BRICS 甲烷排放量 Treemap 图表")

关键说明

  • 新增的country_totals数据框作为顶层节点,每个国家一行,父节点为空
  • segment_nodes作为子节点,父节点设置为对应的国家
  • ids必须唯一,所以子节点用国家-segment的格式命名
  • 颜色映射中给顶层国家节点统一设置了灰色,你可以根据需求调整

内容的提问来源于stack exchange,提问作者Joaquin G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:27:17