0

I want to add total sample size of each facet to geom_histogram.Expect output as below:
enter image description here
After read this post ,I write script as below:

iris %>% 
  ggplot(.,mapping=aes(x=Sepal.Length))+
  geom_histogram(binwidth= 0.1)+
  stat_summary(fun = median, fun.max = length,
               geom = "text", aes(label = after_stat(max)), vjust = -1) +
  facet_wrap(~Species)

But get error:Error: stat_summary requires the following missing aesthetics: y.
How to solve this problem?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
kittygirl
  • 2,255
  • 5
  • 24
  • 52

1 Answers1

4

You can try this:

iris %>% left_join(iris %>% group_by(Species) %>% summarise(N=n()))%>%
  mutate(Label=paste0(Species,' (Sample size = ',N,')')) %>%
  ggplot(.,mapping=aes(x=Sepal.Length))+
  geom_histogram(binwidth= 0.1)+
  facet_wrap(~Label)

It will add a label with sample size to facets:

enter image description here

Update

You can also try:

iris %>% add_count(.,Species) %>% group_by(Species) %>% mutate(n=ifelse(row_number(n)!=1,NA,n)) %>%
  ggplot(.,mapping=aes(x=Sepal.Length))+ 
  geom_histogram(binwidth= 0.1)+ 
  facet_wrap(~Species)+ 
  geom_text(aes(label=n,y=8),size=5,vjust=-0.5)

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • @kittygirl You can but you will have to define the position! – Duck Jul 15 '20 at 22:45
  • `iris %>% add_count(.,Species) %>% ggplot(.,mapping=aes(x=Sepal.Length))+ geom_histogram(binwidth= 0.1)+ facet_wrap(~Species)+ geom_text(aes(label=n,y=8),size=2)` is fine,but `n` repeated each histogram,how to let it show only once? – kittygirl Jul 15 '20 at 22:46
  • @kittygirl Ready! I have updated the solution as you wanted :) – Duck Jul 15 '20 at 22:56