Ggplot2: cut on a column function

Could not find an answer to this question - in ggplot2 is it possible to facet on the column function, and not on the column value directly?

Simple reproducible example:

Sample data:

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

It works:

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

It does not mean:

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

One solution is to add a face-only column. It 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 this without adding a new column to data.frame?

+6
source share
1 answer

I came up with a compromise solution, which is a compromise between the @Nathan and @ Jaffal arguments posted in the comments 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}) 
+2
source

Source: https://habr.com/ru/post/958550/


All Articles