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 865
小蘑菇
小蘑菇 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)) 
    
    0 讨论(0)
  • 2021-01-16 09:29

    With minimal modification, the following code (only last ggplot)

    dd <- plot_data_prepr(dat = dfr2, groupvar = "grpA", mainvar = "x1")
    
    lookup <- unique(dd$grp_tot)
    
    plusN <- function(string) {
      label <- paste0(string, ' (N = ',lookup,')')
      label
    }
    
    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 = plusN)) 
    

    gives this output:

    Please note that this works regardless of the number of groups within grpA.

    0 讨论(0)
提交回复
热议问题