ggplot2 + facet_: Reverse axes for some facets?

by ErinMcJ   Last Updated January 18, 2018 23:26 PM

I've got three subplots I want to put together into one plot, and faceting would be a natural way to do it. However, one of these subplots would be easier/more natural to read with a reversed x-axis (whereas I'd like to leave the others alone). Is there a way to accomplish this using facet_grid() or facet_wrap()?

The other alternative I've considered is grid.arrange(), and the chief problem I've run into there is getting it to align the subplots based on plot area (inside the axes), rather than based on the edges of the images. (My axis titles and labels are not the same size, so the default behavior is fairly ugly.)

Edited to add a MWE with some data for context. Here, since larger is "better" for the beta and R-squared subplots, it would be more natural to reverse the axis for the p subplot. (In this case it would probably also be better to add the log transform to that scale, but my real problem doesn't need to get that fancy.)

df <- data.frame(z=c(rep("R-squared",15),rep("p",15),rep("beta",15)),
                 x=c(runif(15),exp(-runif(15,1,10)),rnorm(15,1,0.5)),
                 y=rep(letters[1:15],3))
plot <- ggplot(df) + geom_point(aes(x=x,y=y)) + facet_grid(.~z, scales="free_x", switch="x")


Answers 1


Here's a solution using patchwork

library(ggplot2)
library(dplyr)
df <- data.frame(z=c(rep("R-squared",15),rep("p",15),rep("beta",15)),
                 x=c(runif(15),exp(-runif(15,1,10)),rnorm(15,1,0.5)),
                 y=rep(letters[1:15],3))

p1 <- ggplot(filter(df, z == "beta"), aes(x, y)) +
  geom_point() 

p2 <- ggplot(filter(df, z == "p"), aes(x, y)) +
  geom_point() +
  scale_x_reverse() +
  theme(axis.title.y = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank())

p3 <- ggplot(filter(df, z == "R-squared"), aes(x, y)) +
  geom_point() +
  theme(axis.title.y = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank())

#devtools::install_github("thomasp85/patchwork")
library(patchwork)
p1 + p2 + p3

patchwork_plot

Daniel Anderson
Daniel Anderson
January 18, 2018 23:25 PM

Related Questions


splitting or removing graphs after arrangeGrob

Updated June 11, 2015 22:11 PM


ggplot2: add distribution jitter near the legend bar

Updated December 01, 2017 23:26 PM

Lock aspect ratio on part of grid

Updated February 14, 2018 03:26 AM