I had a problem adding percentatges to a barplot with ggplot2
I was trying this code:
ggplot(TFM, aes(x=EmbryoQuality, y=prop.table(stat(count)), fill=Group, label=scales::percent(prop.table(stat(count))))) + geom_bar(position=position_dodge2()) + theme(legend.position="bottom") + geom_text(stat_count, position = position_dodge2(.9), vjust=1.6, color="white", size=3.5) + scale_y_continuous(label= scales::percent) + labs(x=EmbryoQuality, y=Percentatges, fill = Group)
And this one:
ggplot(TFMqb, aes(label=EmbryoQuality, fill=Group)) + geom_bar(stat_identity, position=position_dodge2()) + theme(legend.position="bottom") + geom_text(aes(label=EmbryoQuality), vjust=1.6, color="white", size=3.5)
And I was receiving either one of this messages:
-
Error:
mapping
must be created byaes()
, -
geom_text requires the following missing aesthetics: y,
-
stat_count() can only have an x or y aesthetic.
THE CORRECT CODE IS THIS ONE:
ggplot(TFMqe, aes(x= EmbryoQuality, group=Group)) +
geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count", alpha=0.7, position = position_dodge2()) +
geom_text(aes(label = scales::percent(..prop..),
y= ..prop.. ), position = position_dodge2(.9), color = "white", size = 3.5, vjust = 1.6, stat= "count") +
labs(y = "Percent", fill="EmbryoQuality") +
facet_grid(~Group) +
scale_y_continuous(labels = scales::percent) +
theme(legend.position = "none")
And the final result is this barplot (the quality in pdf or jpeg is much better!):