想要在[a,b]之间绘制函数,并在同一图上阴影[c,d]下的区域,其中c和d位于a和b之间 [英] Want to plot a function between [a,b] and on the same plot shade the area under [c,d] where c and d lie between a and b

查看:41
本文介绍了想要在[a,b]之间绘制函数,并在同一图上阴影[c,d]下的区域,其中c和d位于a和b之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot绘制函数,我可以这样做.例如y = x.我在-1和4之间进行绘图.效果很好.在同一张图上,我现在想在1到3之间的曲线下阴影.我无法使其正常工作,也找不到任何文档.有人可以帮我吗?

I'm trying to plot a function using ggplot, which I can do. For example y = x. I plot between -1 and 4. Works great. On the same graph I now want to shade the area under the curve between 1 and 3. I cannot get it to work, nor can I find any documentation. Can someone help me?

我正在尝试的骨架代码:

Skeleton code that I'm trying:

eq<-function(x){(x)}

ggplot(data.frame(x=c(-1,4)),aes(x)) + 
stat_function(fun=eq,geom="line",color="red") + 
stat_function(fun=eq,geom="area",fill="blue")

我尝试了所有不同的排列.如果有一种方法可以将第二个stat_function限制为其他域,则可能会起作用.有什么想法吗?

I tried all different permutations. If there was a way to limit the second stat_function to a different domain it might work. Any ideas?

推荐答案

看来, stat_function 在整个数据范围内工作,而不是使用提供的特定值.一种选择是首先生成要绘制的数据,然后将其传递给特定的 geom _ * .但是,如果您真的想使用 stat_function ,则可能需要做更多的工作.一种方法是创建两个函数,其中之一将输出限制为所需的范围.

It appears that stat_function is working over the full range of data, rather than with the particular values supplied. One option is to generate the data you want to plot first, then pass it to a specific geom_*. However, if you really want to stay with stat_function, you may need to do a bit more work around. One approach would be to create two functions, one of which limits the outputs to the range you want.

eq<-function(x){(x)}
eqB<-function(x){ifelse(x < 3 & x > 0, x, NA)}

ggplot(data.frame(x=c(-1,4)),aes(x)) + 
  stat_function(fun=eq,geom="line",color="red") + 
  stat_function(fun=eqB,geom="area",fill="blue")

一个更强大的解决方案是创建一个接受范围限制的函数,然后使用 args 传递这些限制:

A more robust solution is to create a single function that accepts range limits, then pass those in using args:

eqC <- function(x,upr = max(x), lwr = min(x)){
  ifelse(x <= upr & x >= lwr, x, NA)
}

ggplot(data.frame(x=c(-1,4)),aes(x)) + 
  stat_function(fun=eqC,geom="line",color="red") + 
  stat_function(fun=eqC,geom="area",fill="blue"
                , args = list(upr = 3, lwr = 0))

这两个都生成如下图:

这篇关于想要在[a,b]之间绘制函数,并在同一图上阴影[c,d]下的区域,其中c和d位于a和b之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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