在ggplot2中轻松添加'(all)'facet到facet_wrap?

时间:2013-09-21 14:10:26

标签: r ggplot2

我的数据在facet_wrap documentation

中看起来像这个例子

http://docs.ggplot2.org/current/facet_wrap-29.png

我想使用所有数据填写整个视图的最后一个方面。

是否可以通过facet_wrap轻松添加“总”方面?将保证金添加到facet_grid很容易,但facet_wrap中不存在该选项。

注意:如果您想要上图中的象限,则需要使用facet_grid,这需要ncol的{​​{1}}或nrow个参数。

3 个答案:

答案 0 :(得分:8)

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)

enter image description here

答案 1 :(得分:6)

我更喜欢稍微替代的方法。实际上,在创建绘图之前会复制数据,并为所有数据添加一组新数据。我编写了以下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 :(得分:-3)

你可以尝试&#34;保证金&#34; facet_wrap中的选项如下:

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)
相关问题