I want to add total sample size of each facet to geom_histogram
.Expect output as below:
After read this post https://stackoverflow.com/a/46289861/7936836 ,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)
但得到错误:Error: stat_summary requires the following missing aesthetics: y
.
如何解决这个问题呢?
你可以试试这个:
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)
它将向构面添加带有样本大小的标签:
Update
您还可以尝试:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)