分组数据的 ggplot 构面

ggplot facets on grouped data

我有一个数据框(如下所示的 df),我想为其绘制基于某些分组(CycleNumber 和象限)的 x 和 y 变量的均值。

分组后,我想绘制多面 xy 图(基于 CycleNumber 分组)。然而,ggplot2 代码 returns 一个错误,我无法修复它。
非常感谢任何帮助。

set.seed(1234)
df <- data.frame(CycleNumber = c(rep("Cut1",10), rep("Cut2",10), rep("Hike1",10),rep("Hike2",10) ),
                                 x= rnorm(n=40, mean =0, sd = 1), 
                                 y= rnorm(n=40, mean = 0,sd=1)
                 )


> head(df)
  CycleNumber          x          y
1        Cut1 -1.2070657  1.4494963
2        Cut1  0.2774292 -1.0686427
3        Cut1  1.0844412 -0.8553646
4        Cut1 -2.3456977 -0.2806230
5        Cut1  0.4291247 -0.9943401
6        Cut1  0.5060559 -0.9685143

## Below is the function to calculate the quadrant in XY scatter plot

which_quadrant <- function(x, y, xintercept, yintercept, pool.along = "none") {
  z <- ifelse(x >= xintercept & y >= yintercept,
              1L, 
              ifelse(x >= xintercept & y < yintercept,
                     2L,
                     ifelse(x < xintercept & y < yintercept,
                            3L,
                            4L
                     )
              )
  )
  if (pool.along == "x") {
    z <- ifelse(z %in% c(1L, 4L), 1L, 2L)
  } else if (pool.along == "y") {
    z <- ifelse(z %in% c(1L, 2L), 1L, 4L)
  }
  z
}

df.quadrant <- df %>% mutate(quadrant = which_quadrant(x=x, y=y, xintercept = 0, yintercept = 0))

> head(df.quadrant)
  CycleNumber          x          y quadrant
1        Cut1 -1.2070657  1.4494963        4
2        Cut1  0.2774292 -1.0686427        2
3        Cut1  1.0844412 -0.8553646        2
4        Cut1 -2.3456977 -0.2806230        3
5        Cut1  0.4291247 -0.9943401        2
6        Cut1  0.5060559 -0.9685143        2

df.quadrant %>% group_by(CycleNumber, quadrant) %>% summarise(xmean = mean(x), ymean = mean(y)) %>% 
ggplot(aes(x=xmean, y = ymean )) + geom_point()

上面的 ggplot2 代码在没有分面的情况下工作。但是如果我尝试使用代码

进行分面
df.quadrant %>% group_by(CycleNumber, quadrant) %>% summarise(xmean = mean(x), ymean = mean(y)) %>% 
ggplot(aes(x=xmean, y = ymean )) + geom_point() + facet_grid(CycleNumber)

我收到错误

Error in grid_as_facets_list(rows, cols) : object 'CycleNumber' not found

请帮忙。

我的菜鸟错误

df.quadrant %>% group_by(CycleNumber, quadrant) %>% summarise(xmean = mean(x), ymean = mean(y)) %>%
  ggplot(aes(x=xmean, y = ymean , shape = CycleNumber)) + geom_point() + geom_quadrant_lines() + facet_grid(CycleNumber~.,)

而且有效!