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
474 views
in Technique[技术] by (71.8m points)

r - How to overlay two geom_bar?

I'm trying to overlay 2 the bars from geom_bar derived from 2 separate data.frames.

dEQ
   lab perc
1  lmP 55.9
2  lmN 21.8
3   Nt  0.6
4 expG  5.6
5 expD  0.0
6 prbN 11.2
7 prbP  5.0

and

LMD
   lab perc
1  lmP 16.8
2  lmN  8.9
3   Nt  0.0
4 expG  0.0
5 expD  0.0
6 prbN  0.0
7 prbP  0.0

The first plot is:

p <- ggplot(dEQ, aes(lab, perc)) + 
     xlab(xlabel) + ylab(ylabel) +
     geom_bar(stat="identity", colour="blue", fill="darkblue")  + 
     geom_text(aes(vecX, vecYEQ+1.5, label=vecYlbEQ), data=dEQ, size=8.5)  + 
     theme_bw() +
     opts(axis.text.x = theme_text(size = 20, face = "bold", colour = "black")) +
     opts(axis.text.y = theme_text(size = 20, face = "bold", colour = "black")) +
     coord_flip() + 
     scale_y_continuous(breaks=c(0,10,20,30,40,50,60),
                        labels=c("0","","20","","40","","60"), 
                        limits = c(0, 64), expand = c(0,0))
print(p)

but I want to overplot with another geom_bar from data.frame LMD

ggplot(LMD, aes(lab, perc)) + 
    geom_bar(stat="identity", colour="blue", fill="red", add=T)

and I want to have a legend.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

here is an example:

p <- ggplot(NULL, aes(lab, perc)) + 
  geom_bar(aes(fill = "dEQ"), data = dEQ, alpha = 0.5) +
  geom_bar(aes(fill = "LMD"), data = LMD, alpha = 0.5)
p

enter image description here

but I recommend to rbind them and plot it by dodging:

dEQ$name <- "dEQ"
LMD$name <- "LMD"
d <- rbind(dEQ, LMD)
p <- ggplot(d, aes(lab, perc, fill = name)) + geom_bar(position = "dodge")

enter image description here


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

...