简体   繁体   English

ggplot2 使用计数的条形图标签

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM