如何使用ggplot2为R中的每个bar在geom_bar上添加标签

时间:2021-07-27 13:47:09

I've found this, How to put labels over geom_bar in R with ggplot2, but it just put labels(numbers) over only one bar.

我发现了这个,如何用ggplot2在R中把标签放在geom_bar上,但是它只在一个bar上放标签(数字)。

Here is, let's say, two bars for each x-axis, how to do the same thing?

这是,假设,每条x轴有两个条,如何做同样的事情?

My data and code look like this:

我的数据和代码是这样的:

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

Then, we'll get: 如何使用ggplot2为R中的每个bar在geom_bar上添加标签

然后,我们可以得到:

It seems that the number texts are also positioned in the "dodge" pattern. I've searched geom_text manual to find some information, but cannot make it work.

数字文本似乎也被放置在“减淡”模式中。我已经搜索了地址簿的手册来查找一些信息,但是不能让它工作。

Suggestions?

建议吗?

2 个解决方案

#1


80  

Try this:

试试这个:

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)

如何使用ggplot2为R中的每个bar在geom_bar上添加标签

#2


3  

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

要添加到rcs的答案,如果您想在x为POSIX时使用带有geom_bar()的position_dodge()。ct日期,宽度必须乘以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)

#1


80  

Try this:

试试这个:

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)

如何使用ggplot2为R中的每个bar在geom_bar上添加标签

#2


3  

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

要添加到rcs的答案,如果您想在x为POSIX时使用带有geom_bar()的position_dodge()。ct日期,宽度必须乘以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)