问题
I would like to add a count of observations in each facet to the "title" of each facet. For instance, I have this:
library(tidyverse)
mtcars %>%
ggplot(aes(x = cyl)) + geom_bar()+
facet_wrap(~carb)
and I would like to add the frequencies from the below function to each label
table(mtcars$carb)
1 2 3 4 6 8
7 10 3 10 1 1
Thus the label for 1st row 1st column should be 1; n=7 the 1st row 2nd column 2; n=10 etc...
回答1:
A solution using tidyverse. We can create an updated column to show the count number of carb and then a new column showing updated labels.
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)
回答2:
I wrote this function a while back to label the facet with the standard deviation, mean or count.
#' 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)
来源:https://stackoverflow.com/questions/47544461/how-to-pass-a-count-of-observations-to-the-facet-label