Why is facet_grid placing the distributions in the wrong quadrants?

﹥>﹥吖頭↗ 提交于 2019-12-02 16:41:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31496117/why-is-facet-grid-placing-the-distributions-in-the-wrong-quadrants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!