Home > Enterprise >  One function per facet
One function per facet

Time:01-08

I can plot a function in ggplot2, like so:

library(ggplot2)
ggplot(data.frame(x=0), aes(x))   geom_function(fun = sin)   xlim(c(-5,5))

Can I use ggplot2's facetting to make the plot for multiple functions, one in each facet? (for example sin and cos)

CodePudding user response:

Because fun= is not an aesthetic, I think you cannot facet on it. However, you can faux-facet using the ggplot2 with faux-facets using patchwork

If you prefer the "look" of ggplot2's facets, you can choose this method instead:

gsin <- ggplot(data.frame(x=0, fun="sin"), aes(x))  
  facet_wrap(~fun)  
  geom_function(fun = sin)  
  xlim(c(-5,5))
gtan <- ggplot(data.frame(x=0, fun="tan"), aes(x))  
  facet_wrap(~fun)  
  geom_function(fun = tan)  
  xlim(c(-5,5))
gsin   gtan

ggplot2 faux-facets using real facet labels

All of this so far has the effect of facet_*(scales="free_y") (because we fixed xlim(.)). If you want to mimic faceting more closely, you need to control the limits of all facets:

ylims <- c(-1, 1)
gsin <- ggplot(data.frame(x=0, fun="sin"), aes(x))  
  facet_wrap(~fun)  
  geom_function(fun = sin)  
  xlim(c(-5,5))  
  scale_y_continuous(limits = ylims)
gtan <- ggplot(data.frame(x=0, fun="tan"), aes(x))  
  facet_wrap(~fun)  
  geom_function(fun = tan)  
  xlim(c(-5,5))  
  scale_y_continuous(name = NULL, guide = NULL, limits = ylims)
gsin   gtan
# Warning: Removed 22 row(s) containing missing values (geom_path).

ggplot2 faux-facet with y-limits under control

Technically you are not required here to set the y-limits on all, but ... unless you know with certainty that the limits on unconstrained y-axes will be what you need, it is possible that they could be slightly off. For instance, if you change the initial function (in a quick hack) to be 2*sin(x) but forget to update the remaining facets' y-limits, then your plots will be lying. It's best to set the limits in a single place (ylims <- ...) and reference in all plots.

CodePudding user response:

Looks like you in fact can facet by the function if you feed each layer its own data with the faceting variable specified:

library(ggplot2) # using ggplot2 3.3.5
ggplot(data.frame(x=0), aes(x))   
  geom_function(fun = sin, data = data.frame(x = -5:5, fun = "sin"))  
  geom_function(fun = cos, data = data.frame(x = -5:5, fun = "cos"))  
  facet_wrap(~fun)
  

enter image description here

  •  Tags:  
  • Related