ggplot2使用计数的条形图标签

问题描述

在下面的代码中,如何在显示条数的每个条形上添加标签?谢谢

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()
         )

enter image description here

解决方法

您可以尝试以下方法:

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()
  )

输出:

enter image description here

您还可以使用以下方法为标签尝试其他位置:

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()
  )

输出:

enter image description here