[英]ggplot2 barplot labels using counts
In the code below, how do I add label to each bar showing its count?在下面的代码中,如何将 label 添加到显示其计数的每个条形中? 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()
)
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: Output:
You can also try a different position for labels with this:您还可以尝试使用不同的 position 使用以下标签:
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: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.