[英]How to put labels over geom_bar for each bar in R with ggplot2
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 上,但它只是将标签(数字)放在一个条上。
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:然后,我们会得到:
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.
我搜索了geom_text 手册以找到一些信息,但无法使其工作。
Suggestions?建议?
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)
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, eg,要添加到 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.