如何使用ggplot2将R中的每个条形图放在geom_bar上 [英] How to put labels over geom_bar for each bar in R with ggplot2
本文介绍了如何使用ggplot2将R中的每个条形图放在geom_bar上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找到了这个,来查找一些信息,但无法做到工作。
建议?
解决方案
试试这个:
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)
< img src =https://i.stack.imgur.com/1Zllw.pngalt =ggplot输出>
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.
Here is, let's say, two bars for each x-axis, how to do the same thing?
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.
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)
这篇关于如何使用ggplot2将R中的每个条形图放在geom_bar上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文