如何使用ggplot2遮蔽曲线下的区域 [英] How to shade a region under a curve using ggplot2

查看:147
本文介绍了如何使用ggplot2遮蔽曲线下的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  xv <-seq(

我试图用ggplot2生成一个类似于这个R图形的图。 (xv,yv,type =l)
多边形(c(xv [xv≤0.4,0.01))
yv <-dnorm(xv,2,0.5)
plot 1.5],1.5),c(yv [xv≤1.5],yv [xv == 0]),col =gray)

这就像我用ggplot2得到的一样:

  x <-seq (0.0,0.1699,0.0001)
ytop< -dnorm(0.12,0.08,0.02)
MyDF< -data.frame(x = x,y = dnorm(x,0.08,0.02))
p <-qplot(x = MyDF $ x,y = MyDF $ y,geom =line)
p + geom_segment(aes(x = 0.12,y = 0,xend = 0.12,yend = ytop ))

我想遮蔽x = 0.12以外的尾部区域。我将如何使用ggplot或qplot来做到这一点?一般来说,如何勾画曲线下的任何子集,无论是尾巴,还是将两个区域划分为不同区域的两条任意线之间?$ b $
$ b


$ b

感谢您的任何建议。 使用您想要阴影的区域创建多边形 p>

 ##首先替换数据并添加坐标以使其阴影为y = 0 
阴影<-rbind(c (0.12,0),子集(MyDF,x> 0.12),c(MyDF [nrow(MyDF),X],0))

#然后使用这个新的data.frame geom_polygon
p + geom_segment(aes(x = 0.12,y = 0,xend = 0.12,yend = ytop))+
geom_polygon(data = shade,aes(x,y))


I've been trying to use ggplot2 to produce a plot similar to this R graphic:

xv<-seq(0,4,0.01)
yv<-dnorm(xv,2,0.5) 
plot(xv,yv,type="l") 
polygon(c(xv[xv<=1.5],1.5),c(yv[xv<=1.5],yv[xv==0]),col="grey") 

This is as far as I've gotten with ggplot2:

x<-seq(0.0,0.1699,0.0001)   
ytop<-dnorm(0.12,0.08,0.02)
MyDF<-data.frame(x=x,y=dnorm(x,0.08,0.02))
p<-qplot(x=MyDF$x,y=MyDF$y,geom="line") 
p+geom_segment(aes(x=0.12,y=0,xend=0.12,yend=ytop))

I would like to shade the tail region beyond x=0.12. How would I do this using ggplot or qplot?

Broadly, how does one shade any subset under the curve, whether a tail, or between two arbitrary lines dividing the region into distinct areas?

Thanks for any advice.

解决方案

Create a polygon with the area you want to shade

#First subst the data and add the coordinates to make it shade to y = 0
shade <- rbind(c(0.12,0), subset(MyDF, x > 0.12), c(MyDF[nrow(MyDF), "X"], 0))

#Then use this new data.frame with geom_polygon
 p + geom_segment(aes(x=0.12,y=0,xend=0.12,yend=ytop)) +
     geom_polygon(data = shade, aes(x, y))

这篇关于如何使用ggplot2遮蔽曲线下的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆