how to use labeller() functions to get column totals to appear in the label of a facet when using the facet_grid() function in ggplot2

后端 未结 2 887
小蘑菇
小蘑菇 2021-01-16 08:52

here\'s a data set to give context to my question:

library(tidyr); library(dplyr); library(ggplot2)
set.seed(1)
dfr2 <- tibble(x1 = factor(sample(letters[1         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 09:16

    I think the cleanest approach for a situation like yours would be to use a lookup table for your labeller instead of a function:

    lookup <- c(
      grp1 = "grp1 (N = 20)",
      grp2 = "grp2 (N = 30)"
    )
    
    ggplot(plot_data_prepr(dfr2, "grpA", "x1"), aes(x = x1, y = pct2, fill = x1)) +
      geom_bar(stat = 'identity') +
      ylim(0,1) +
      geom_text(aes(label=pct_lab, y = pct_pos + .02)) +
      facet_grid(. ~ grpA, labeller = labeller(grpA = lookup))
    

    If you think your group totals might change in the future, you can also auto-generate the labels by processing the data beforehand and extracting the necessary parts:

    data <- plot_data_prepr(dfr2, "grpA", "x1")
    
    lookup <- c(
        grp1 = paste0("grp1 (N = ", data$grp_tot[data$grpA == "grp1"][1], ")"),
        grp2 = paste0("grp2 (N = ", data$grp_tot[data$grpA == "grp2"][1], ")")
    )
    
    ggplot(data, aes(x = x1, y = pct2, fill = x1)) + 
      geom_bar(stat = 'identity') +
      ylim(0,1) +
      geom_text(aes(label=pct_lab, y = pct_pos + .02)) +
      facet_grid(. ~ grpA, labeller = labeller(grpA = lookup)) 
    

提交回复
热议问题