1

I would like to make a plot using facet_wrap where the axes can vary for each panel but within a panel the x and y axes should be the same scale.

e.g. see the following plots

df <- read.table(text = "
x y g
1 5 a
2 6 a
3 7 a
4 8 a
5 9 b
6 10 b
7 11 b
8 12 b", header = TRUE)

library(ggplot2)

ggplot(df, aes(x=x,y=y,g=g)) +
  geom_point() +
  facet_wrap(~ g) # all axes 1-12

ggplot(df, aes(x=x,y=y,g=g)) +
  geom_point() +
  facet_wrap(~ g, scales = "free")
 # fee axes, y & y axes don't match per panel

What i want is for panel a the x and why axes both to be 1-8 and for panel b the x and y axes both to range from 5 - 12.

Is this possible?

user1320502
  • 2,510
  • 5
  • 28
  • 46
  • I wonder if you are keen to draw two separate figures and use `grid.arrange()`. That would be one way to go, I think. – jazzurro Feb 27 '15 at 11:04
  • @jazzurro I was thinking about employing `grid.arrange` although it seems a bit frustrating when you have 8-12 panels. – user1320502 Feb 27 '15 at 11:10
  • I see your point. But, I'd be happy to use ncol and nrow in `grid.arrange` rather than thinking about how I can manipulate x and y axis for each figure. – jazzurro Feb 27 '15 at 11:20
  • Yeah i just wrote a apply to do this, I'll just find out how to match the x and y limits for a ggplot then i could use that – user1320502 Feb 27 '15 at 11:28

3 Answers3

4

Using this answer you could try the following:

dummy <- data.frame(x = c(1, 8, 5, 12), y = c(1, 8, 5, 12), g = c("a", "a", "b", "b"))
ggplot(df, aes(x=x,y=y)) +
 geom_point() +
 facet_wrap(~ g, scales = "free") + 
 geom_blank(data = dummy)

enter image description here

Community
  • 1
  • 1
DatamineR
  • 10,428
  • 3
  • 25
  • 45
3

Another solution is trick the axes for individual facet_wrap() plots by adding invisible points to the plots with x and y reversed so that the plotted data is "square", e.g.,

library(ggplot2)
p <- ggplot(data = df) + 
       geom_point(mapping = aes(x = x, y = y)) + 
       geom_point(mapping = aes(x = y, y = x), alpha = 0) + 
       facet_wrap( ~ g, scales = "free")
print(p)

You could also use geom_blank(). You don't need dummy data.

Simon Woodward
  • 1,946
  • 1
  • 16
  • 24
1

This wasn't an option when the question was asked, but these days I would highly recommend patchwork for combining plots.

slackline
  • 2,295
  • 4
  • 28
  • 43