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 894
小蘑菇
小蘑菇 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: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.

提交回复
热议问题