显示每个方面组中的观察数 ggplot2

Show number of observation in each facet group ggplot2

我有这个 ggplot 代码,我认为到目前为止一切顺利,符合我的预期。

    bi_tr%>%
  filter(!is.na(bi_tr$`13e Toilet type`)) %>%

  ggplot(aes(x=`12 Income`,fill=`13e Toilet type`,na.rm = TRUE))+ #this fill comment goes to define legend
  geom_histogram(binwidth=50,color="black")+ #setting default color for aes in histogram
  facet_wrap(vars(fill=`13e Toilet type`),nrow=3)+ #make 1 column and 3 rows
  labs(x="Income (USD/month)",y="Frequency",title = "Income by Toilet Type")+ #make title of axis and title
  theme(legend.title=element_blank(),strip.text.x = element_blank())+ #strip text.x deletes the title in each group
  scale_fill_manual(values =c("blue","yellow","grey"))+#set fill color
  theme(legend.justification=c(1,.5), legend.position=c(1,.5))   #setting legend location

但我想在每个方面组显示我的总数据观察,我已经尝试 stat_summary 和 fun.data=give.n 但结果显示 "object 'give.n' not found"

请在这里帮助一些新手...感谢一百万

没有可重现的数据集,很难确定您问题的确切解法,但您可以尝试在 geom_text.

中添加计数

这里有一个例子来说明这一点:

df <- data.frame(Income = sample(0:1000,900, replace = TRUE),
                 Type = rep(LETTERS[1:3], each = 300))

library(dplyr)
library(ggplot2)

df %>% 
  filter(!is.na(Type)) %>%
  ggplot(aes(x = Income, fill = Type))+
  geom_histogram(binwidth = 50, color = "black")+
  facet_wrap(~Type, nrow = 3)+
  labs(x="Income (USD/month)",y="Frequency",title = "Income by Toilet Type")+ #make title of axis and title
  theme(legend.title=element_blank(),
        strip.text.x = element_blank())+ #strip text.x deletes the title in each group
  scale_fill_manual(values =c("blue","yellow","grey"))+
  theme(legend.justification=c(1,.5), legend.position=c(1,.5))+   #setting legend location
  geom_text(data = df%>% filter(!is.na(Type)) %>% count(Type), 
            aes(label = paste("Count:",n), y = Inf, x  = -Inf), vjust = 1, hjust = 0)

因此,根据您的代码进行调整,它应该如下所示:

bi_tr%>%
  filter(!is.na(`13e Toilet type`)) %>%  
  ggplot(aes(x=`12 Income`,fill=`13e Toilet type`,na.rm = TRUE))+ #this fill comment goes to define legend
  geom_histogram(binwidth=50,color="black")+ #setting default color for aes in histogram
  facet_wrap(~`13e Toilet type`,nrow=3)+ #make 1 column and 3 rows
  labs(x="Income (USD/month)",y="Frequency",title = "Income by Toilet Type")+ #make title of axis and title
  theme(legend.title=element_blank(),strip.text.x = element_blank())+ #strip text.x deletes the title in each group
  scale_fill_manual(values =c("blue","yellow","grey"))+#set fill color
  theme(legend.justification=c(1,.5), legend.position=c(1,.5))+   #setting legend location
  geom_text(data = bi_tr%>% filter(!is.na(`13e Toilet type`)) %>% count(`13e Toilet type`), 
            aes(label = paste("Count:",n), y = Inf, x  = -Inf), vjust = 1, hjust = 0)

它是否回答了您的问题?

如果没有,请按照本 post 中提供的指南提供数据集的可重现示例 bi_trHow to make a great R reproducible example