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?
While facet_grid shows the labels at the margins of the facet plot, facet_wrap creates a label for each plot panel.
Faceting is the process that split the chart window in several small parts (a grid), and display a similar chart in each section. Each section usually shows the same graph for a specific group of the dataset. The result is usually called small multiple.
facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.
Faceting is a great data visualization technique that uses “small multiples” i.e. the use of same type of plots multiple times in a panel. Each “small multiple” is a same type of plot but for a different group or category in the data. ggplot2 makes it really easy to make such “small multiples” with faceting.
In this article, we will see how to create a faceted line-graph using ggplot2 in R Programming Language. In ggplot2, geom_line () function is used to create a line graph. Facets can be created after adding separate methods along with required parameters.
For specifying nothing, we use dot parameter like facet_grid (. ~ Facets). This will return vertical facets on the plot and to draw horizontal facets, we simply have to interchange the dot parameter and facets vector in facet_grid () function.
Instead of faceting with a variable in the horizontal or vertical direction, facets can be placed next to each other, wrapping with a certain number of columns or rows. The label for each plot will be at the top of the plot.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With