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

如何实现可正常运行的Plotly树形图并添加百分比符号

修复Plotly树形图并添加百分比标签

问题根源

  1. 数据类型错误:n列是因子(factor)类型,Plotly树形图的values参数需要数值型数据,这是代码无法运行的主要原因。
  2. 父节点配置错误:parents = NA不符合树形图的结构要求,单层树形图需将父节点设为空字符串""。
  3. 未实现百分比符号需求:原代码未在标签和悬停提示中添加%符号。

修复后的完整代码

library(plotly)

dtd7 <- structure(
  list(
    topic = structure(
      c(9L, 8L, 4L, 7L, 2L, 6L, 1L, 3L,
        5L, 10L, 13L, 11L, 12L),
      .Label = c("Owners' Equivalent Rent of Residences", 
                 "Rent of Primary Residence",
                 "New Vehicles", "Used Cars and Trucks",
                 "Cereals And bakery Prouducts",
                 "Motor Vehicle Maintenance and Repair", 
                 "Airline Fares", 
                 "Apparel", 
                 "Alcoholic Bevreages", 
                 "Hospital Services",
                 "Tobacco and Smoking", 
                 "Physicans Services", 
                 "Gasoline All Types",
                 "Electricity",
                 "Utility (Piped) Gas Services",
                 "Nonalcohoholic Beverages and Beverage Materials",
                 "Food Away From Home",
                 "Meats Poultry Fish and",
                 "Fruits and Vegetables",
                 " Dairy and Related Products",
                 "Cereals And bakery Prouducts",
                 "Other Foods at Home"),
      class = "factor"
    ),
    n = structure(
      c(4L, 3L, 9L, 11L, 12L, 2L, 1L, 6L, 10L, 5L,
        7L, 8L, 1L),
      .Label = c("6.7", "6.9", "1.4", "3.8", "19.2", "8.5", "12.1", "1.1", "5", "2.9", 
                 "6.3", "7.7", "0.7",
                 "8.9", "3.4", "10.4", "2.9", "5.3", "0.1", "0.4", "1.4", "3.4","3.3"),
      class = "factor"
    )
  ),
  class = "data.frame",
  row.names = c(NA,-13L)
)

# 转换因子列到数值型
dtd7$n <- as.numeric(as.character(dtd7$n))

p <- plot_ly(
  dtd7,
  labels = ~topic,
  parents = "",  # 单层树形图的父节点设置为空字符串
  values = ~n,
  type = 'treemap',
  # 自定义悬停提示,添加%符号
  hovertemplate = "Category: %{label}<br>Percent: %{value}%<extra></extra>",
  # 生成带%的文本标签
  text = ~paste0(n, "%"),
  textinfo = "text"  # 设置显示自定义文本
)

p

核心修复点说明

  • 数据类型转换:使用as.numeric(as.character(dtd7$n))将因子类型的百分比数据转为数值型,解决Plotly无法识别数值的问题。
  • 树形结构修正:将parents参数设为空字符串"",确保Plotly能正确渲染单层树形图。
  • 百分比符号添加:
    • 悬停模板中直接在%{value}后拼接%符号,优化悬停提示效果;
    • 通过text = ~paste0(n, "%")生成带%的标签文本,并用textinfo = "text"设置在树形图块上显示该文本。

内容的提问来源于stack exchange,提问作者Data and AI Nerd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:44:51