Plotly树形图无法渲染求助:运行代码仅显示空白界面
问题原因
你的treemap显示空白,核心问题是没有正确设置树形层级结构:
- Plotly的treemap需要通过
parents参数定义节点间的父子关系,你把parents设为NA,相当于所有节点都没有父节点,Plotly无法构建有效的树形布局,所以渲染空白。
修复方案
要让treemap正常显示,需要给所有节点指定一个共同的根节点,或者定义合理的层级。下面是两种可行的修改方式:
方式1:添加根节点(所有节点为同级子节点)
创建一个根标签,然后让所有现有节点的父节点都指向这个根:
labels = c("总类别", # 添加根节点 "Owners' Equivalent Rent of Residences", "Rent of Primary Residence", "New Vehicles", "Used Cars and Trucks", "Cereals And Bakery Products", "Motor Vehicle Maintenance and Repair", "Airline Fares", "Apparel", "Alcoholic Beverages", "Hospital Services", "Tobacco and Smoking", "Physicians Services", "Gasoline All Types", "Electricity", "Utility (Piped) Gas Services", "Nonalcoholic Beverages and Beverage Materials", "Food Away From Home", "Meats Poultry Fish and Eggs", "Fruits and Vegetables", "Dairy and Related Products", "Cereals And bakery Products", "Other Foods at Home") # 根节点没有父节点(设为""),其他所有节点的父节点都是"总类别" parents = c("", rep("总类别", length(labels)-1)) fig <- plot_ly( type='treemap', labels=labels, # 根节点值设为所有子节点的总和,Plotly也会自动计算,可省略 values= c(sum(c(6.7, 6.9, 1.3, 3.8, 3.4, 8.5, 12.1, 1.1, 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)), 6.7, 6.9, 1.3, 3.8, 3.4, 8.5, 12.1, 1.1, 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), parents=parents, textinfo="label+value+percent parent+percent root", domain=list(column=0)) fig
方式2:定义自定义层级(按类别分组)
如果你的数据有自然分组(比如住房、交通、食品等),可以手动设置parents构建多层结构:
labels = c("总类别", "住房类", "交通类", "食品类", "医疗类", "其他类", # 一级分组 "Owners' Equivalent Rent of Residences", "Rent of Primary Residence", # 住房子类 "New Vehicles", "Used Cars and Trucks", "Motor Vehicle Maintenance and Repair", "Gasoline All Types", # 交通子类 "Cereals And Bakery Products", "Food Away From Home", "Meats Poultry Fish and Eggs", "Fruits and Vegetables", "Dairy and Related Products", "Other Foods at Home", # 食品子类 "Hospital Services", "Physicians Services", # 医疗子类 "Airline Fares", "Apparel", "Alcoholic Beverages", "Tobacco and Smoking", "Electricity", "Utility (Piped) Gas Services", "Nonalcoholic Beverages and Beverage Materials") parents = c("", rep("总类别",5), # 一级分组的父节点是总类别 rep("住房类",2), rep("交通类",4), rep("食品类",6), rep("医疗类",2), rep("其他类",7)) values = c(sum(c(6.7,6.9,1.3,3.8,3.4,8.5,12.1,1.1,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)), 6.7+6.9, 1.3+3.8+8.5+8.9, 3.4+5.3+0.1+0.4+1.4+3.4+3.3, 6.3+0.7, 12.1+1.1+2.9+7.7+3.4+10.4+2.9, 6.7,6.9,1.3,3.8,8.5,8.9,3.4,5.3,0.1,0.4,1.4,3.4,3.3,6.3,0.7,12.1,1.1,2.9,7.7,3.4,10.4,2.9) fig <- plot_ly( type='treemap', labels=labels, values=values, parents=parents, textinfo="label+value+percent parent+percent root", domain=list(column=0)) fig
额外注意点
labels、values、parents三个向量的长度必须完全一致,否则会报错或渲染异常;- 根节点的
parents必须设为空字符串"",不能是NA; - 如果不需要根节点,也可以把所有节点的
parents设为空字符串,但这种情况下treemap会把每个节点当作独立根,布局可能不符合预期。
内容的提问来源于stack exchange,提问作者Data and AI Nerd
相关产品推荐
相关产品推荐

