0

I am plotting a range of different data measured on the same individuals next to each other in facets. For some types of data a positive value is "good" and for some a negative value is "good". The latter types of variables are usually plotted with flipped y-axes. Is it possible to modify axis directions in individual facets with ggplot?

dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20))

ggplot(dat, aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')

For example, could I do the above plot with the y-axis for B reversed?

Lars Lau Raket
  • 1,905
  • 20
  • 35

2 Answers2

3

I'm not sure if that's possible, so I would opt for a solution using the grid.arrange function from the gridExtra package.

library(gridExtra)
library(ggplot2)

dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20),
                  stringsAsFactors = FALSE)

p_A <- ggplot(subset(dat, type == 'A'), aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')+
    scale_y_continuous(breaks = c(-1,0,1))
p_B <- ggplot(subset(dat, type == 'B'), aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')+
    scale_y_reverse(breaks = c(-1,0,1))

grid.arrange(p_A, p_B, nrow = 1)

enter image description here

bouncyball
  • 10,631
  • 19
  • 31
  • Thank you for the answer. I had a feeling that this was the only real solution that didn't require massive amounts of coding. I'll accept it as it is probably the best solution available, but I had really hoped for something that generalized well to more complex faceting with `facet_grid`. – Lars Lau Raket May 15 '17 at 07:37
3

This can now also be achieved using the ggh4x package or the facetscales package (see here for facetscales approach):

library(ggh4x)

dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20))

scales <- list(
  scale_y_continuous(),
  scale_y_reverse()
  )

ggplot(dat, aes(x, y)) + 
  geom_point() +
  facet_wrap( ~ type, scales = 'free_y') +
  facetted_pos_scales(y = scales)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
QAsena
  • 603
  • 4
  • 9