用ggplot图填充曲线下 [英] Filling under the a curve with ggplot graphs

查看:131
本文介绍了用ggplot图填充曲线下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个图,其法线函数从x = -2到x = 2填充在曲线从-2到0的下面。
我尝试过ggplot2

I would like to create a graph with the normal function from x=-2 to x=2 filled under the curve from -2 to 0. I've tried with ggplot2

qplot(c(-2, 2), stat="function", fun=dnorm, geom="line") +
+ geom_area(aes(xlim=c(-2,0)),stat="function", fun=dnorm)

但是我改为完全填充此图(黑色)

But I get this graph completely filled instead (the black colour)

我如何获得只能从-2填充到0的情节?

How can I get a plot filled only from -2 to 0?

欢迎使用其他选项或软件包。

Other options or packages are welcome.

我已经我也只尝试了一个带有ggplot和filled选项的命令,但我也无法得到它。

我知道有些人使用多边形来做到这一点,但结果并不那么柔和美观。

I've also tried with only one command with ggplot and filled option but I can't get it either.
I know some people does it using polygons but the result is not so soft and nice.

PD:我重复一遍,我要寻找的解决方案不是预先生成x,y坐标,而是直接使用stat = function,fun = dnorm函数或类似。因此,我的问题不是重复的。

PD: I repeat, the solution I'm looking for involves not generating x,y coordinates beforehand but using directly the function with stat="function", fun=dnorm or similar. Thus, my question is not a duplicate.

我也尝试过

ggplot(NULL,aes(x=c(-2,2))) +  geom_area(aes(x=c(-2,0)),stat="function", fun=dnorm, fill="red") +
geom_area(aes(x=c(0,2)),stat="function", fun=dnorm, fill="blue")  

但是,它再次用单一颜色蓝色填充了所有曲线。红一半似乎已被覆盖。

But again it fills all the curve with a single color, blue. The red half seems to be overwritten. The same with geom_ribbon and other options.

推荐答案

尝试一下:

ggplot(data.frame(x = c(-2, 2)), aes(x)) +
  stat_function(fun = dnorm) + 
  stat_function(fun = dnorm, 
                xlim = c(-2,0),
                geom = "area") 

这篇关于用ggplot图填充曲线下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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