如何使用ggplot2为R中的每个条形图放置geom_bar上的标签

Pur*_*ney 82 r bar-chart ggplot2

我发现了这个,如何在带有ggplot2的R中将标签放在geom_bar上,但它只是将标签(数字)放在一个条上.

这就是说,每个x轴有两个条,怎么做同样的事情?

我的数据和代码如下所示:

dat <- read.table(text = "sample Types Number
sample1 A   3641
sample2 A   3119
sample1 B   15815
sample2 B   12334
sample1 C   2706
sample2 C   3147", header=TRUE)

library(ggplot2)
bar <- ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
  geom_bar(position = 'dodge') + geom_text(aes(label=Number))
Run Code Online (Sandbox Code Playgroud)

然后,我们将得到: 在此输入图像描述

似乎数字文本也定位在"闪避"模式中.我搜索了geom_text手册来查找一些信息,但无法使其正常工作.

建议?

rcs*_*rcs 120

试试这个:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
Run Code Online (Sandbox Code Playgroud)

ggplot输出

  • (+1) 您还可以在 `position()` 语句之后添加 `vjust = -0.5`,以便将值放置在条形上方。 (3认同)
  • 非常感谢,顺便说一句,代码建议设置`ymax`,所以'aes(x =类型,y =数字,填充=样本,ymax = 16000)`,将为y轴产生更宽的上部区域,因此15815会得到更好的表现. (2认同)
  • 此答案具有更新的语法http://stackoverflow.com/questions/33079500/geom-text-with-dodged-barplot?noredirect=1&amp;lq=1 (2认同)
  • @Seymour `geom_text(..., angle=-90)` (2认同)

mat*_*mat 5

要添加到 rcs 的答案中,如果您想在 x 是 POSIX.ct 日期时将position_dodge() 与 geom_bar() 一起使用,则必须将宽度乘以 86400,例如,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
Run Code Online (Sandbox Code Playgroud)