Easily add an '(all)' facet to facet_wrap in ggplot2?
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)
I prefer a slightly alternative approach. Essentially, the data is duplicated before creating the plot, with a new set of data added for the all data. I wrote the following CreateAllFacet
function to simplify the process. It returns a new dataframe with the duplicated data and an additional column 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)
}
The benefit of adding the new column facet
to the original data is that it still allows the variable cylinder
to be used to colour the points in the plot within the aesthetics:
df <- CreateAllFacet(mpg, "cyl")
ggplot(data=df, aes(x=displ,y=hwy)) +
geom_point(aes(color=cyl)) +
facet_wrap(~ facet) +
theme(legend.position = "none")