将计数值添加到 "qplot" 直方图

Adding Count Value to "qplot" histogram

我想知道如何将计数值添加到由 qplot 绘制的直方图?

    qplot(cluster_name$km.out1.cluster, geom="histogram",binwidth = 0.5,
main = "Histogram for clusters Number", xlab = "cluster number", fill=I("blue")) + 
  theme(plot.title = element_text(hjust = 0.5)) 

我尝试添加

+ stat_bin(aes(y=..count..,label=..count..), geom="text", vjust=-.5, binwidth = 0.5)

然而,这个命令会在 x 轴上添加一堆零,这不是我想要的。我试图删除 label 但收到一条错误消息。请看下面的结果图片:

为了防止标记零计数,您可以将 ifelse 语句添加到 stat_bingeom_text,将标签设置为零计数的空字符串。

使用 mtcars 作为示例数据试试这个:

library(ggplot2)

qplot(mtcars$mpg, geom="histogram",binwidth = 0.5,
      main = "Histogram for clusters Number", xlab = "cluster number", fill=I("blue")) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  stat_bin(aes(y=..count..,label = ifelse(..count.. > 0, ..count.., "")), geom="text", vjust=-.5, binwidth = 0.5)