Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

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.

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: enter image description here

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

ggplot output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...