在“曲线”内使用用户定义的函数功能在R图形 [英] Using user-defined functions within "curve" function in R graphics

查看:188
本文介绍了在“曲线”内使用用户定义的函数功能在R图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成具有不同总面积的正态分布密度图(总计为1)。使用下面的函数,我可以指定lambda - 它给出了相对区域:

$ pre $ s $ cdn sdnorm < - function(x,mean = 0,sd = 1,lambda = 1){lambda * dnorm(x,mean = mean,sd = sd)}

然后我想用不同的参数来绘制函数。使用ggplot2,这段代码有效:

  require(ggplot2)
qplot(x,geom =blank)+ stat_function(fun = sdnorm,args = list(mean = 18,sd = 4,lambda = 0.30)+
stat_function(fun = sdnorm,args = list(mean = 8,sd = 2,lambda = 0.7) )



但我真的想在基本的R图形中做到这一点,我认为我需要使用曲线功能。但是,我很努力地让这个工作。

解决方案

如果你看看<$ c $的帮助文件C>?曲线,你会看到第一个参数可以是许多不同的东西:


一个函数,或一个调用或一个表达式,它被写为x的一个函数,它将评估一个与x长度相同的对象。

这意味着你可以指定第一个参数作为函数名或表达式,所以你可以这样做:

  curve( sdnorm)

来获得该函数的默认参数图。否则,重新创建你想要做的ggplot2表示:

  curve(sdnorm(x,mean = 8,sd = 2 
曲线(sdnorm(x,mean = 18,sd = 4,lambda = 0.30),add = TRUE)



结果:


I am needing to produce normally distributed density plots with different total areas (summing to 1). Using the following function, I can specify the lambda - which gives the relative area:

sdnorm <-  function(x, mean=0, sd=1, lambda=1){lambda*dnorm(x, mean=mean, sd=sd)}

I then want to plot up the function using different parameters. Using ggplot2, this code works:

require(ggplot2)
qplot(x, geom="blank") + stat_function(fun=sdnorm,args=list(mean=8,sd=2,lambda=0.7)) +
  stat_function(fun=sdnorm,args=list(mean=18,sd=4,lambda=0.30))

but I really want to do this in base R graphics, for which I think I need to use the "curve" function. However, I am struggling to get this to work.

解决方案

If you take a look at the help file for ? curve, you'll see that the first argument can be a number of different things:

The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.

This means you can specify the first argument as either a function name or an expression, so you could just do:

curve(sdnorm)

to get a plot of the function with its default arguments. Otherwise, to recreate your ggplot2 representation you would want to do:

curve(sdnorm(x, mean=8,sd=2,lambda=0.7), from = 0, to = 30)
curve(sdnorm(x, mean=18,sd=4,lambda=0.30), add = TRUE)

The result:

这篇关于在“曲线”内使用用户定义的函数功能在R图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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