简体   繁体   English

将观察总数添加到条形图

[英]Adding total count of observations to barplot

I am currently working with survey data with 250 columns.我目前正在处理包含 250 列的调查数据。 A sample of my data looks like this:我的数据样本如下所示:

q1 <- factor(c("yes","yes","no","yes",NA,"yes","no","yes"))
q2 <- factor(c("Albania","USA","Albania","Albania","UK",NA,"UK","Albania"))
q3 <- factor(c(0,1,0,0,1,1,0,0))
q4 <- factor(c(0,NA,NA,NA,1,NA,0,0))
q5 <- factor(c("Dont know","Prefer not to answer","Agree","Disagree",NA,"Agree","Agree",NA))
q6 <- factor(c(1,NA,3,5,800,NA,900,2))

data <- data.frame(q1,q2,q3,q4,q5,q6)

In order to loop through all columns and create list of barplots showing distribution of answers, I used code below:为了遍历所有列并创建显示答案分布的条形图列表,我使用了以下代码:

barplot_list <- lapply(names(data), function(variable) {
  ggplot(
    data = data,
    mapping = aes(.data[[variable]])
  ) +
    geom_bar(width = 0.6, fill = "#0096FF") +
    labs(x = variable, y = "response count") +
    geom_text(aes(label=..count..),stat='count',position=position_dodge(0.9),hjust=-0.1)+
    scale_fill_brewer(palette = "Set2") +
    theme_bw() +
    theme(panel.grid.major.y = element_blank()) +
    coord_flip()
})

Now I want to add total count of observations to each barplot.现在我想将观察总数添加到每个条形图。 Total count can be shown in legend or inside chart or in caption.总计数可以显示在图例或内部图表或标题中。 I tried adding following line of code: geom_text(stat = "count",aes(label = after_stat(sum(count))))我尝试添加以下代码行: geom_text(stat = "count",aes(label = after_stat(sum(count))))

But this shows total count on top of each bar.但这显示了每个栏顶部的总数。 Is there a way to modify my code so that "Total = N" (N standing for total observations for each column(excluding NAs) in dataset) is shown somewhere in the plot?有没有办法修改我的代码,以便在 plot 的某处显示“Total = N”(N 代表数据集中每一列(不包括 NA)的总观察值)? Thank you very much beforehand!非常感谢你!

the number of observations is going to be the same for every plot, because it's the number of rows of the dataframe... (8 in your example)每个 plot 的观察次数将相同,因为它是 dataframe 的行数...(在您的示例中为 8)

can add it in the caption like this:可以像这样在标题中添加它:

+ labs(caption = paste("Total =", nrow(data)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM