我不知道有什么简单的方法可以做到这一点。有一种困难的方法,包括大量的数据重塑。
从本质上讲,您可以为右侧边距、底部边距和合计创建单独的数据帧,然后逐行将它们绑定到主数据帧上。在此过程中,您还必须添加一个指示符列来说明该行是否为边距,并添加另一个列来提供带有计数的标签。最后,必须将贴面变量转换为因子:
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)