[英]ggplot2: Plot coefficients in coefficient plot using facet_grid
[英]How to add marginal totals to a ggplot2 facet_grid plot using a different geom
我不知道有什么簡單的方法可以做到這一點。 有一個困難的方法,其中包括大量的數據整形。
本質上,您為右邊距、底部邊距和總計創建單獨的數據框,然后將它們按行綁定到主數據框。 在此過程中,您還必須添加一個指示列來說明該行是否為邊距,以及另一個提供帶有計數的標簽。 最后,分面變量必須轉換為因子:
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.