问题描述
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()
)
解决方法
您可以尝试以下方法:
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()
)
输出:
您还可以使用以下方法为标签尝试其他位置:
ggplot(iris) +
geom_bar(aes_string(x="Species"),position = position_dodge(width = 0.9),vjust=-0.5)+
theme(axis.text.y = element_blank(),axis.title.y = element_blank()
)
输出: