Home > Enterprise >  ggplot facets on grouped data
ggplot facets on grouped data

Time:11-24

I have a dataframe (df as below) for which I want to plot the means of x and y variables based on some groupings (CycleNumber and quadrant).

After the groupings, I want to plot a faceted xy plot (based on the CycleNumber grouping). However, the ggplot2 code returns an error and I am unable to fix it.
any help is highly appreciated.

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()

The above ggplot2 code works without faceting. BUT If I try to facet using the code

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

I get the error

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

Kindly help.

CodePudding user response:

rookie error by me

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~.,)

and it works!

  • Related