代码之家  ›  专栏  ›  技术社区  ›  JasonAizkalns

如何使用不同的geom将边际总计添加到ggplot2 facet_grid图

  •  0
  • JasonAizkalns  · 技术社区  · 4 年前

    假设我们有一个简单的 facet_grid 情节

    library(ggplot2)
    
    ggplot(mtcars, aes(hp, mpg)) +
      geom_point() +
      facet_grid(cyl ~ am, switch = "y")
    

    我想添加两者的边际总数(即每行和每列的记录数) cyl am 到情节。然而,我想改变 geom 。理想情况下,我希望这些 文本 。这看起来可能与此类似:

    enter image description here

    这可能吗?我试过一些东西 facet_grid(..., margins = TRUE) ,但尚未成功。也许这会更容易通过预先计算的总数,然后将图形与 grid ?

    0 回复  |  直到 4 年前
        1
  •  2
  •   Allan Cameron    4 年前

    我不知道有什么简单的方法可以做到这一点。有一种困难的方法,包括大量的数据重塑。

    从本质上讲,您可以为右侧边距、底部边距和合计创建单独的数据帧,然后逐行将它们绑定到主数据帧上。在此过程中,您还必须添加一个指示符列来说明该行是否为边距,并添加另一个列来提供带有计数的标签。最后,必须将贴面变量转换为因子:

    library(ggplot2)
    library(dplyr)
    
    data <- mtcars %>% 
              mutate(label = "",
                     plot = TRUE,
                     cyl   = as.character(cyl), 
                     am    = as.character(am)) %>% 
              select(cyl, am, hp, mpg, label, plot)
    
    mar1 <- data %>% 
      group_by(cyl) %>% 
      summarize(am = "(All)", hp = mean(range(data$hp)),
                mpg = mean(range(data$mpg)), 
                label = as.character(n()), plot = FALSE)
    
    mar2 <- data %>% 
      group_by(am) %>% 
      summarize(cyl = "(All)", hp = mean(range(data$hp)), 
                mpg = mean(range(data$mpg)), 
                label = as.character(n()), plot = FALSE)
    
    mar3 <- data %>% 
      summarize(cyl = "(All)", am = "(All)", 
                hp = mean(range(data$hp)), 
                mpg = mean(range(data$mpg)),
                label = as.character(n()), plot = FALSE)
    
    
    big_data <- bind_rows(data, mar1, mar2, mar3) %>%
      mutate(cyl = factor(cyl, levels = c("4", "6", "8", "(All)")),
             am = factor(am, levels = c("0", "1", "(All)")))
    

    完成后,您可以使用big绘制结果 geom_label s(实际上是无限填充)为您的边距。

    ggplot(big_data[big_data$plot,], aes(hp, mpg, label = label)) +
      geom_point() +
      geom_label(data = big_data[!big_data$plot,], size = 15, 
                 label.padding = unit(1, "npc")) +
      facet_grid(cyl ~ am, switch = "y", drop = FALSE)
    

    enter image description here