Reputation: 671
In the code below, how do I add label to each bar showing its count? Thanks
library(ggplot2)
data(iris)
ggplot(iris) +
geom_bar(aes_string(x="Species"), fill="steelblue") +
# geom_text(aes(label="Species")) + # does not work
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank()
)
Upvotes: 0
Views: 98
Reputation: 39613
You can try this:
library(tidyverse)
#Data
data(iris)
#Plot
ggplot(iris) +
geom_bar(aes_string(x="Species"), fill="steelblue") +
geom_text(data= iris %>% group_by(Species) %>% summarise(N=n()),
aes(x=Species,y=N,label=N),position = position_stack(vjust = 0.5))+
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank()
)
Output:
You can also try a different position for labels with this:
ggplot(iris) +
geom_bar(aes_string(x="Species"), fill="steelblue") +
geom_text(data= iris %>% group_by(Species) %>% summarise(N=n()),
aes(x=Species,y=N,label=N),position = position_dodge(width = 0.9),vjust=-0.5)+
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank()
)
Output:
Upvotes: 1