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

如何将Plotly绘制的Treemap迁移至ggplot2实现?

问题

我用Plotly创建了一个树形图(Treemap),代码和数据如下:

library(plotly)
library(dplyr)
library(ggplot2)

df1<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler", 
                              "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda", 
                              "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac", 
                              "Porsche", "Toyota", "Valiant", "Volvo"), count = c(1L, 1L, 1L, 
                                                                                  1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L, 
                                                                                  2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl", 
                                                                                                                                   "data.frame"))
df1$test<-"CARS"

treemap<-plot_ly(data = df1,
                 type= "treemap",
                 values= ~count,
                 labels= ~manuf,
                 parents=  ~test,
                 domain= list(column=0),
                 name = " ",
                 textinfo="label+value+percent parent")  %>%
  layout(title="", 
         annotations =
           list(x = 0, y = -0.1,
                title = "", 
                text = " ",
                showarrow = F,
                xref='paper',
                yref='paper'))

treemap

该树形图将所有品牌作为子类别归属到"CARS"父类别下,区块大小对应count值,同时显示标签、数值和占父类的百分比。我尝试用ggplot2复现,但自行编写的代码无法生成正确的树形图:

# Prepare data in hierarchical format
df1_hierarchical <- df1 %>%
  mutate(parent = "CARS")

    # Calculate coordinates for treemap
    df1_hierarchical <- df1_hierarchical %>%
      mutate(
        x0 = 0,
        x1 = cumsum(count) / sum(count),
        y0 = 0,
        y1 = 1
      )
    
    # Plot treemap using ggplot2
    ggplot(df1_hierarchical) +
      geom_rect(aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = manuf)) +
      geom_text(aes(x = (x0 + x1) / 2, y = (y0 + y1) / 2, label = manuf), size = 3) +
      scale_fill_manual(values = rainbow(nrow(df1_hierarchical))) + # Color scale
      labs(title = NULL, fill = NULL) +
      theme_void() +
      coord_fixed()

需要找到在ggplot2中复现该树形图的正确方法。

解决方案

你手动计算坐标的方式只能生成横向条形布局,并非真正的树形图。要在ggplot2中实现和Plotly一致的树形图效果,推荐使用treemapify包(专门生成树形图布局坐标),配合ggfittext自动调整文本排版,避免重叠。

步骤1:安装并加载依赖包

install.packages(c("treemapify", "ggfittext"))
library(treemapify)
library(ggfittext)
library(dplyr)
library(ggplot2)

步骤2:预处理数据

先计算每个品牌占父类的百分比,用于拼接显示文本:

df1 <- df1 %>%
  mutate(percent_parent = paste0(round(count / sum(count) * 100, 1), "%"))

步骤3:绘制树形图

ggplot(df1, aes(area = count, fill = manuf, 
                label = paste0(manuf, "\n", count, "\n", percent_parent))) +
  geom_treemap() +
  geom_treemap_text(place = "centre", grow = TRUE, reflow = TRUE, size = 10) +
  scale_fill_manual(values = rainbow(nrow(df1))) +
  theme(legend.position = "none") +
  labs(title = NULL)

代码说明

  • geom_treemap():根据area参数指定的count值自动生成优化后的树形图布局,逻辑和Plotly的treemap一致。
  • geom_treemap_text():自动将文本置于区块中心,grow = TRUE会根据区块大小动态调整字号,reflow = TRUE自动换行避免文本溢出。
  • 拼接的label参数实现了和Plotly中textinfo="label+value+percent parent"完全一致的显示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:25:58