Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot - facet by function output

Tags:

r

ggplot2

facet

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.

like image 357
Ken Williams Avatar asked Sep 04 '12 21:09

Ken Williams


People also ask

What is a facet plot in ggplot2?

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.

How to reorder bar plots with facetting using Ggplot2 in R?

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)

How does ggplot work with missing faceting variables?

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.

How to control the layout of a ggplot?

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.


1 Answers

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)
like image 166
Alex Brown Avatar answered Oct 07 '22 17:10

Alex Brown