Palace Chan
Palace Chan

Reputation: 9213

Why is facet_grid placing the distributions in the wrong quadrants?

When using facet_grid(x ~ y) with ggplot2 I've seen in various examples and read in the documentation that the x variable is laid out vertically and the y variable horizontally. However, when I run the following:

set.seed(1)
b = c(rnorm(10000,mean=0,sd=0.5),rnorm(10000,mean=5,sd=0.5),
      rnorm(10000,mean=7,sd=0.5),rnorm(10000,mean=10,sd=0.5))
x = c(rep('xL', 20000), rep('xR',20000))
y = c(rep('yL',10000), rep('yR',20000), rep('yL',10000))
foo = data.frame(x=x,y=y,b=b)

ggplot(data=foo, aes(foo$b)) + 
  geom_histogram(aes(y=..density..),breaks=seq(-5,12,by=.2),col='steelblue',fill='steelblue2') + 
  geom_density(col='black') + 
  facet_grid(x ~ y, scales='free_y')

I get the below (sorry for the quality). And even though, from above, the distribution with mean 10 is the one with (x,y) of 'xR,xL' that one appears in the bottom right quadrant which has labels 'xR,yR'. What am I doing wrong?

enter image description here

Upvotes: 0

Views: 419

Answers (1)

Akhil Nair
Akhil Nair

Reputation: 3284

Change aes(foo$b) to aes(x = b) to make sure the aesthetics are mapping correctly.

You want to make sure ggplot is finding the column labelled b from the correct scope i.e. from the data that it has been passed. For example, it may be the case that ggplot rearranged your data when you passed it, so mapping the variable foo$b no longer aligns with what you want.

I'm not saying this is what happened - just an example of why calling the aesthetic from the correct scope is important.

Upvotes: 2

Related Questions