我不知道有什么简单的方法可以做到这一点。有一个困难的方法,其中包括大量的数据重塑。
基本上,您为右边距、下边距和总计创建单独的数据框,然后将它们逐行绑定到主数据框。在途中,您还必须添加一个指示列来说明该行是否是边距,另一个来提供带有计数的标签。最后,必须将分面变量转换为因子:
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_labels(具有有效的无限填充)为您的边距绘制结果。
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)