6

Couldn't find an answer to this -- in ggplot2, is it possible to facet on a function of a column, rather than on the value of the column directly?

Simple reproducible example:

Sample data:

df=data.frame(dat=c(1,2,5,5,7))

This works:

ggplot(df, aes(x=1:5, y=dat, colour=factor(dat > 3))) + 
       geom_point() + facet_grid(dat ~ .)

This does not:

ggplot(df, aes(x=1:5, y=dat, colour=factor(dat > 3))) + 
       geom_point() + facet_grid((dat > 3) ~ .)

One solution is to add a column just for the facet. This works:

df$facet=df$dat>3
ggplot(df, aes(x=1:5, y=dat, colour=factor(dat > 3))) + 
       geom_point() + facet_grid(facet ~ .)

But is there a way to do it without having to add a new column to the data.frame?

3
  • 3
    What is the problem with adding a new column? I would rather expect that adding a new column is faster because of taking advantage of native R functions and vectorization. Commented Nov 21, 2013 at 10:45
  • 2
    My primary aversion to adding a new column is just that it seems inelegant. ggplot2 can handle coloring by a function of a factor -- what about faceting? What if you want to do do this on several different functions of a factor but not clutter your dataframe with extra columns, or bother with creating and deleting them? Commented Nov 21, 2013 at 11:54
  • 1
    I get your point - I have been there, too - but at the end of the day it is just a cosmetical issue and if you ask me, as much as I enjoy R, it is an inelegant language by design - its purpose is to get the job done well, but not elegantly. Commented Nov 21, 2013 at 12:11

1 Answer 1

2

I've come up with a compromise solution, which is a trade-off between arguments of @Nathan and @Яaffael posted in the comment section.

FacetingFunction <- function(df) {df$dat > 3}
ArbitraryFacetingPlot <- function(df, FacetingFunction) {
  df$facet <- FacetingFunction(df)
  p <- ggplot(df, aes(x=1:5, y=dat, colour=factor(dat > 3))) + 
    geom_point() + 
    facet_grid(facet ~ .)
  df$facet <- NULL
  p
}

ArbitraryFacetingPlot(df, FacetingFunction)
ArbitraryFacetingPlot(df, function(df) {df$dat==5})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.