如何在ggplot2的facet_wrap中轻松添加“(全部)”facet?

14
我有一些类似于facet_wrap文档中示例的数据:


(图片来源: ggplot2.org)

我想用所有数据填充最后一个细分面板,以呈现总体视图。

有没有一种简单的方法可以在facet_wrap中添加“总计”细分面板?使用facet_grid很容易添加边距,但facet_wrap中不存在该选项。

注意:如果要像上面的图表那样制作四象限,则无法使用facet_grid,因为它需要facet_wrap中的ncolnrow参数。

3个回答

15
library(ggplot2)

p <- qplot(displ, hwy, data = transform(mpg, cyl = as.character(cyl)))
cyl6 <- subset(mpg, cyl == 6)
p + geom_point(data = transform(cyl6, cyl = "7"), colour = "red") +
  geom_point(data = transform(mpg, cyl = "all"), colour = "blue") +
  facet_wrap(~ cyl)

输入图像描述


1
完美!你知道把 all 改成另一个字符串有多难吗?非常感谢你的帮助。 - Fr.
完美,符合预期。之前不知道transform的技巧(同时也在学习mutate)。再次感谢您的帮助。 - Fr.

9

我更倾向于另一种方法。基本上,在创建图表之前,数据会被复制,添加一个新的数据集到所有数据中。我编写了下面的CreateAllFacet函数来简化这个过程。它返回一个新的数据框,其中包括重复的数据和一个额外的列facet

library(ggplot2)

#' Duplicates data to create additional facet
#' @param df a dataframe
#' @param col the name of facet column
#'  
CreateAllFacet <- function(df, col){
  df$facet <- df[[col]]
  temp <- df
  temp$facet <- "all"
  merged <-rbind(temp, df)

  # ensure the facet value is a factor
  merged[[col]] <- as.factor(merged[[col]])

  return(merged)
}

添加新列facet到原始数据的好处是,它仍然允许使用变量cylinder来为美学中的点着色:
df <- CreateAllFacet(mpg, "cyl")

ggplot(data=df, aes(x=displ,y=hwy)) +
  geom_point(aes(color=cyl))  +
  facet_wrap(~ facet) +
  theme(legend.position = "none")

enter image description here


-2

您可以尝试在facet_wrap中使用“margins”选项,如下所示:

library(ggplot2)

p <- qplot(displ, hwy, data = transform(mpg, cyl = as.character(cyl)))
cyl6 <- subset(mpg, cyl == 6)
p + geom_point(data = transform(cyl6, cyl = "7"), colour = "red") +
  facet_wrap(~ cyl, margins=TRUE)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接