【问题标题】:ggplot2 barplot labels using countsggplot2条形图标签使用计数
【发布时间】:2020-08-11 15:43:16
【问题描述】:

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

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你可以试试这个:

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

    输出:

    【讨论】:

    • 我有一个后续问题。在函数bar.plot <- function(df, y) {ggplot(df) + geom_bar(aes_string(x=y)) + geom_text(data=df %>% group_by(df$y) %>% summarise(N=n()), aes(x=y, y=N, label=N))} 中定义并使用bar.plot(iris, "Species") 调用时,我无法使其工作。问题似乎出在aes(x=y,...)。我不太明白group_by() %>% summarise() 的输出是如何分配给aes(x= 的。有什么帮助吗?谢谢
    • 您可以尝试隔离类似newdf <- df %>% group_by(df$y) %>% summarise(N=n()) 的任务,然后在geom_text() 内部使用,还可以检查dplyr() 中字符串的评估,只要看起来该函数也因为@ 而出现问题987654335@。 newdf 保存计数结果,然后添加为标签!
    • x 应该是您在df[y] 中的名称。您应该检查names(newdf) 并查看详细信息。如果出现奇怪的名称,您可以使用 rename 并给它一个特定的名称,然后添加到 x in geom_text()
    • 如果你用标准名称重命名列看起来会更好,然后你很容易设置成geom!尝试newdf %>% rename(x=Species,y=N) -> newdf,然后设置为仅aes(x=x,y=y,label=y)
    • 为什么不使用这个:geom_text(aes(x=Species, label = ..count..),stat = "count", position = position_stack(vjust = 0.5))
    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多