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

r - Shading confidence intervals manually with ggplot2

I have manually created a data set of life expectancies with accompanying 95% confidence bands. I plot these over the time scale but would prefer the bands to be shaded rather than dotted lines. Code shown:

p1 = ggplot()
p2 = p1 + geom_line(aes(x=pl$Time, y=pl$menle), colour="blue")
p3 = p2 + geom_line(aes(x=pl$Time, y=pl$menlelb), colour="blue", lty="dotted")
p4 = p3 + geom_line(aes(x=pl$Time, y=pl$menleub), colour="blue", lty="dotted")

Is there a simple way to shade the interval rather than just have the lines?? If I'm missing something simple I apologise in advance but I cannot find anything to indicate a simple way of doing this.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It would be helpful if you provided your own data, but I think the following does what you are after.

First, create some dummy data:

##I presume the lb and ub are lower/upper bound
pl = data.frame(Time = 0:10, menle = rnorm(11))
pl$menlelb = pl$menle -1
pl$menleub = pl$menle +1

Then create the plot. The shaded region is created using geom_ribbon:

ggplot(pl, aes(Time)) + 
  geom_line(aes(y=menle), colour="blue") + 
  geom_ribbon(aes(ymin=menlelb, ymax=menleub), alpha=0.2)

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

1.4m articles

1.4m replys

5 comments

56.9k users

...