如何获得显示在此 ggplot barplot 条形图上的计数

How do I get the counts displayed on the bars of this ggplot barplot

我有一个名为 'res' 的 'data.frame',它看起来像这样:

name property count
john 7 3
john 6 3
john 2 3
tim 4 2
tim 1 2
kim 9 1

换句话说,名字栏有某人的名字。 属性 是指向他们拥有的 属性 包裹的钥匙。 count 列是我生成的一列,它只包含他们拥有的属性数量。我试图制作一个条形图来显示他们每个人拥有多少(占总财产的百分比)。到目前为止,我有以下内容:

ggplot(data=res, aes(x=reorder(name, count)) + geom_bar(aes(y=(..count..)/sum(..count..))) + scale_y_continuous(labels=percent_format()) + coord_flip()

然后我得到一个条形图,john 是顶部和最长的条形图,tim 在他下方,然后是 kim。这几乎是我想要的,但我想在每个栏内显示计数变量(所以在约翰栏上它会说 3)但我不确定该怎么做?

到目前为止,我尝试了以下方法:

ggplot(data=res, aes(x=reorder(name, count), y=count) + geom_bar(aes(y=(..count..)/sum(..count..))) + scale_y_continuous(labels=percent_format()) + coord_flip() + geom_text(aes(label=count))

但是虽然这算数,但它似乎使我的 x 轴爆炸并将我的条一直压缩到左侧。

您可以将 stat_bingeom=text 一起使用,这样您就可以访问用于缩放位置的隐藏变量

ggplot(data=res, aes(x=reorder(name, count), y=count)) +
  geom_bar(aes(y=(..count..)/sum(..count..))) +
  scale_y_continuous(labels=percent_format()) +
  coord_flip() +
  stat_bin(aes(y=..count../sum(..count..), label=..count..), geom="text", hjust=-0.5)