在 R 中绘制连续函数 [英] Plot a continuous function in R

查看:83
本文介绍了在 R 中绘制连续函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在 R 中绘制类似 y = a*b 的内容,其中 y 等于某个常量并且 a,b >0.

How would I plot something like y = a*b in R, where y equals some constant and a,b > 0.

例如a*b=5.它绘制那条线的地方.

So a*b=5 for example. Where it plots that line.

我只见过传入 ab 的值列表并从这些值绘制 y,而不是绘制连续的曲线.

I've only ever seen passing in lists of values for a and b and plotting y from those values, not plotting a continuous curve.

f <- function(a,b) {a*b}

我将如何在 R 中执行以下操作?

How would I do something like the following in R?

f <- function(a,b) {a*b = 5}

推荐答案

这称为参数图.如果您不能或不想根据 x 求解 y(在本例中为 y=5/x),您可以计算网格上的值并让 R 绘制相关的等高线.emdbook 包中的 curve3d 函数为此任务提供了方便的包装器.

This is called a parametric plot. If you can't or don't want to solve for y in terms of x (y=5/x in this case), you can compute the values over a grid and ask R to draw the relevant contour line. The curve3d function from the emdbook package provides a convenient wrapper for this task.

library(emdbook)
curve3d(x*y,sys3d="contour",levels=5,
        xlim=c(0,5),ylim=c(0,5))
curve(5/x,col=2,add=TRUE)

但实际上在基础 R 中也不太难:

But it's actually not too hard to do in base R either:

xvec <- seq(0,5,length=51)
yvec <- seq(0,5,length=51)
z <- outer(xvec,yvec,"*") ## "*" is default but you could specify
                          ## any other _vectorized_ function of two
                          ## arguments ...
contour(xvec,yvec,z,levels=5)

如果您的函数在 x 和 y 中矢量化,您可以 (1) 使用 ?Vectorize 使其矢量化;(2) 在 x 和 y 向量上使用 expand.gridapply 你的函数,并将结果向量折叠回矩阵;(3) 使用嵌套的 for 循环;或者 (4) 放弃并使用 emdbook::curve3d(这就是它的用途).

If your function is not vectorized in x and y, you could (1) use ?Vectorize to make it vectorized; (2) use expand.grid on your x and y vectors, apply your function, and collapse the vector of results back into a matrix; (3) use nested for loops; or (4) just give up and use emdbook::curve3d (that's what it's for).

这篇关于在 R 中绘制连续函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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