簡體   English   中英

如何使用不同的幾何圖形將邊際總數添加到 ggplot2 facet_grid 圖

[英]How to add marginal totals to a ggplot2 facet_grid plot using a different geom

假設我們有一個簡單的facet_grid圖:

library(ggplot2)

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

我想將cylam邊際總數(即每行和每列的記錄計數)添加到圖中。 但是,我想更改底層geom 理想情況下,我希望這些是text 這可能類似於:

在此處輸入圖片說明

這可能嗎? 我已經用facet_grid(..., margins = TRUE)嘗試了一些東西,但還沒有成功。 也許使用預先計算的總數然后將圖形與grid相結合會更容易?

我不知道有什么簡單的方法可以做到這一點。 有一個困難的方法,其中包括大量的數據整形。

本質上,您為右邊距、底部邊距和總計創建單獨的數據框,然后將它們按行綁定到主數據框。 在此過程中,您還必須添加一個指示列來說明該行是否為邊距,以及另一個提供帶有計數的標簽。 最后,分面變量必須轉換為因子:

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)")))

完成后,您可以使用大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)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM