I'm unsure how to facet by a function of the data in the data
element of a ggplot
object. In the following toy example, what I want to do is something like this:
df <- data.frame(x=1:8, y=runif(8), z=8:1)
ggplot(df, aes(x=x, y=y)) + geom_point() + facet_wrap( ~ (z %% 2))
But that gives the error: Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting
.
I can achieve the desired result by transforming the data frame:
ggplot(transform(df, z=z%%2), aes(x=x, y=y)) + geom_point() + facet_wrap( ~ z)
but often it's desirable to not use such a transformation, for instance if I've already been given a ggplot
object and I want to add some ad-hoc faceting to it.
This is a known as a facet plot. This is a very useful feature of ggplot2. The faceting is defined by a categorical variable or variables. Each panel plot corresponds to a set value of the variable. setwd ("~/Documents/Computing with Data/13_Facets/") library (ggplot2) Here, a single categorical variable defines subsets of the data.
In this article, we will discuss how to reorder bar plots with facetting using the ggplot2 package in the R Programming Language. We can draw a facet bar plot by using the geom_col () function with the facet_wrap () function of the ggplot2 package. Syntax: ggplot ( dataframe, aes ( x, y ) ) + geom_col () + facet_wrap (~z)
Here ggplot will do what you expect: it will display the map in every facet: missing faceting variables are treated like they have all values. Here’s a simple example.
We can control the layout with options to the facet_wrap function. We can add an aesthetic for another variable and get one legend. p <- ggplot (data = mpg, aes (x = displ, y = hwy, color = drv)) + geom_point () p + facet_wrap (~cyl) Some of the subsets may exhibit extreme bahavior of a variable causing other facets to plot in uncommunicative ways.
this sounds familiar to me, but I never managed to fix it - I think facet variable handling is just less powerful than aesthetic variable handling.
Addressing your root requirement - to ad-hoc facet an existing ggplot; note that you can replace wholesale the (master) data set of an existing R
ggplot - for instance
myplot %+% transform(myplot$data, z=z%%2)
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