Reputation: 169
I'm trying to make a barplot with two categorical values. This particular thread was very helpful
My code was this
ggplot(DF, aes(Participant.Type, ..count...)) +
geom_bar(aes(fill=Sex), position ="dodge") +
theme_classic() +
ggtitle("Main phenotypes stated for the PCDH19 cohort on GEL") +
scale_fill_viridis(option ="viridis")
This was my resulting graph. I'm now trying to add the count of the particular bars on top - like Female proband is 135, Male proband is 165 and so on. I tried adding different iterations of the geom_text command so I could achieve this. Commands here:
+ geom_text(aes(label= ..count))
+ geom_text(aes(label= Sex))
Could anyone please help?
Upvotes: 0
Views: 72
Reputation: 7626
With some sample data from that question you linked you can do it like this:
library(ggplot2)
library(viridis)
#> Loading required package: viridisLite
Fruit <- c(rep("Apple", 3), rep("Orange", 5))
Bug <- c("worm", "spider", "spider", "worm", "worm", "worm", "worm", "spider")
df <- data.frame(Fruit, Bug)
ggplot(df, aes(Fruit, fill = Bug)) + geom_bar(position = "dodge") +
geom_text(
aes(label = after_stat(count)),
stat = "count",
vjust = -0.5,
position = position_dodge(width = 0.9)
) +
geom_text(
aes(y = after_stat(count), label = Bug),
stat = "count",
vjust = -1.5,
position = position_dodge(width = 0.9)
) +
scale_y_continuous(expand = expansion(add = c(0, 1))) +
scale_fill_viridis(option = "viridis", discrete = TRUE)
A few things to note:
geom_bar
doesn't need ..count..
passed as a y-value - it defaults to countingafter_stat(count)
is the updated form of ..
notationUpvotes: 2
Reputation: 46
I can't test the process without your input data, but here's something for you to give a try:
+ geom_text(stat='count', aes(label=..count..), vjust=-1)
Upvotes: 1