我想在每个方面添加一个观察计数到"标题"每个方面。例如,我有这个:
library(tidyverse)
mtcars %>%
ggplot(aes(x = cyl)) + geom_bar()+
facet_wrap(~carb)
我希望将以下功能的频率添加到每个标签
table(mtcars$carb)
1 2 3 4 6 8
7 10 3 10 1 1
因此,第1行第1列的标签应为1; n=7
第1行第2列2; n=10
等...
答案 0 :(得分:3)
使用db.test.find({},{"fieldC.id":0, fieldB: 0, "_id":0})
的解决方案。我们可以创建一个更新的列来显示tidyverse
的计数,然后创建一个显示更新标签的新列。
carb
答案 1 :(得分:2)
我稍后写了这个函数,用标准偏差,平均值或计数标记了facet。
#' 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)