将树形图从 Plotly 克隆到 ggplot2

问题描述 投票:0回答:1

使用 Plotly,我创建了这个树形图。您可以看到下面的代码和数据。

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

现在,我想在 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 中创建这个树形图吗?

r ggplot2 plotly
1个回答
1
投票

你的尝试是从头开始计算的,但我会使用

treemapify

library(treemapify)
df1 |>
    mutate(
        n = sum(count),
        pc = round(n / sum(df1$count) * 100),
        label = paste0(manuf, "\n", n, "\n", pc, "%"),
        .by = manuf
    ) |>
    ggplot(aes(area = count, fill = manuf)) +
    geom_treemap() +
    geom_treemap_text(aes(label = label), grow = TRUE) +
    theme(
        legend.position = "none"
    )

© www.soinside.com 2019 - 2024. All rights reserved.