2017-11-29 4 views
1

各ファセットの「タイトル」に各ファセットの観測数を追加したいと思います。例えば、私はこれがあります。ファセットラベルに観測回数を渡すにはどうすればいいですか?

library(tidyverse)  

mtcars %>% 
    ggplot(aes(x = cyl)) + geom_bar()+ 
    facet_wrap(~carb) 

を、私はこのように1行1列目のラベルが1; n=7 1行である必要があり、各ラベル

table(mtcars$carb) 
1 2 3 4 6 8 
7 10 3 10 1 1 

に以下の機能からの周波数を追加したいと思います第2欄2; n=10

答えて

2

tidyverseを用いた溶液。更新された列を作成して、カウント番号carbを表示し、更新されたラベルを示す新しい列を作成することができます。

library(tidyverse) 

mtcars %>% 
    group_by(carb) %>% 
    mutate(carb_count = n()) %>% 
    ungroup() %>% 
    mutate(carb_updated = paste0(carb, "; n=", carb_count)) %>% 
    ggplot(aes(x = cyl)) + geom_bar()+ 
    facet_wrap(~carb_updated) 

enter image description here

2

私は、標準偏差とのファセットにラベルを付ける意味かカウントするしばらく前にこの機能を書きました。

#' Function will update the name with the statistic of your choice 
AddNameStat <- function(df, category, count_col, stat = c("sd","mean","count"), dp= 0){ 

    # Create temporary data frame for analysis 
    temp <- data.frame(ref = df[[category]], comp = df[[count_col]]) 

    # Aggregate the variables and calculate statistics 
    agg_stats <- plyr::ddply(temp, "ref", summarize, 
          sd = sd(comp), 
          mean = mean(comp), 
          count = length(comp)) 

    # Dictionary used to replace stat name with correct symbol for plot 
    labelName <- plyr::mapvalues(stat, 
         from=c("sd","mean","count"), 
         to=c("\u03C3", "x", "n")) 

    # Updates the name based on the selected variable 
    agg_stats$join <- paste0(agg_stats$ref, ": ", labelName," = ", 
          round(agg_stats[[stat]], dp)) 

    # Map the names 
    name_map <- setNames(agg_stats$join, as.factor(agg_stats$ref)) 
    return(name_map[as.character(df[[category]])]) 
} 



# Create a label for the facet 
mtcars$label <- AddNameStat(mtcars, "carb", "cyl", stat = "count") 

mtcars %>% 
    ggplot(aes(x = cyl)) + geom_bar()+ 
    facet_wrap(~label) 

enter image description here

関連する問題