Home > Blockchain >  How do I move ggplot strip labels so that there is one on top and one on the right and only label co
How do I move ggplot strip labels so that there is one on top and one on the right and only label co

Time:01-14

Example data:

dat <- tibble(River = c(rep(letters[1:6],27))) %>% 
                mutate(cohort=rep(seq(2007,2015,1),18),
              mu = c(rnorm(54,300,25),
                     rnorm(54,0.5,0.15),
                     rnorm(54,-0.75,0.1)),
              param = c(rep('var1',54), 
                        rep('var2',54),
                        rep('var3',54))) %>% 
  group_by(param) %>% mutate(
              upr = mu 2*sd(mu),
              lwr = mu-2*sd(mu)) 

The data is not exactly how I want it but it shouldn't matter for the question. I am trying to make a 6x3 plot using facet functions from ggplot2 or ggpubr and I've found that facet from ggpubr makes the plot I would like but does not allow the y-scales to be free using the scales argument, which is the same behavior that facet_grid has. Therefore I can utilize facet_wrap and achieve the desired result in terms of a free y-axis scale, and I can move labels to the top or right side but I cannot find a way to only label the columns and rows and separate labels so that my param is labeled on the columns and River is labels on the rows.

In short I would like this plot:

p1 <- ggplot(data = dat)  
  geom_point(aes(x=cohort, y=mu))  
  geom_errorbar(aes(x=cohort, ymin=lwr, ymax=upr),
                width=0)

facet(p1,
      facet.by = c('River', 'param'),
      scales = 'free')
                      

with the y-scale free...like this:

p1   
  facet_wrap(nrow = 6, ncol = 3,
             vars(factor(River),param),
             scales = 'free',
             strip.position = c('right'))

CodePudding user response:

The ggh4x::facet_grid2() function allows for independent scales within columns or rows in a grid layout. Disclaimer: I'm the author of ggh4x.

library(tidyverse)

dat <- tibble(River = c(rep(letters[1:6],27))) %>% 
  mutate(cohort=rep(seq(2007,2015,1),18),
         mu = c(rnorm(54,300,25),
                rnorm(54,0.5,0.15),
                rnorm(54,-0.75,0.1)),
         param = c(rep('var1',54), 
                   rep('var2',54),
                   rep('var3',54))) %>% 
  group_by(param) %>% mutate(
    upr = mu 2*sd(mu),
    lwr = mu-2*sd(mu)) 

p1 <- ggplot(data = dat)  
  geom_point(aes(x=cohort, y=mu))  
  geom_errorbar(aes(x=cohort, ymin=lwr, ymax=upr),
                width=0)

p1  
  ggh4x::facet_grid2(factor(River) ~ param,
                     scales = 'free', independent = "y")

Created on 2022-01-13 by the reprex package (v2.0.1)

  •  Tags:  
  • Related