如何绘制水平二次函数?

时间:2017-02-16 16:42:34

标签: r

我试图在R中绘制一个“横向”或水平二次函数,但我遇到了问题sqrt(-x)当然是一个问题。

eq1 = function(x){ -60*(sqrt(1-x)-1) }
eq2 = function(x){ 60*(sqrt(1-x)+1) }

plot(eq1, 0, 100, add=TRUE, xlim=c(0,1), ylim=c(0,100))
plot(eq2, 0, 100, add=TRUE)

以下是输出图

的示例

enter image description here

来自R控制台的输出:

> eq1 = function(x){ -60*(sqrt(1-x)-1) }
> eq2 = function(x){ 60*(sqrt(1-x)+1) }
> 
> 
> plot(eq1, 0, 100, add=TRUE, xlim=c(0,1), ylim=c(0,100))
Warning messages:
1: In curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab,  :
  'add' will be ignored as there is no existing plot
2: In sqrt(1 - x) : NaNs produced
> plot(eq2, 0, 100, add=TRUE)
Warning message:
In sqrt(1 - x) : NaNs produced

如果我理解正确,那么像这样的二次函数存在域限制。如果是这样,有没有办法将它们合并到R中定义的函数中?或者有更好的方法来绘制这个功能吗?

2 个答案:

答案 0 :(得分:2)

您需要使用x plot.function参数正确定义要绘制函数的范围:

plot(eq1, seq(0, 1, 0.01), xlim=c(0,1), ylim=c(0,100))
plot(eq2, seq(0, 1, 0.01), add=TRUE)

实际上,plot.function非常聪明,即使没有范围,它也能为您解决问题:

plot(eq1, xlim=c(0,1), ylim=c(0,100))
plot(eq2, add=TRUE)

enter image description here

(没有警告。)

答案 1 :(得分:1)

除非我错过了什么......为什么不使用abs

eq1 = function(x){ -60*(sqrt(abs(1-x))-1) }
eq2 = function(x){ 60*(sqrt(abs(1-x))+1) }



plot(eq1, 0, 100, add=FALSE, xlim=c(0,1), ylim=c(0,100))
plot(eq2, 0, 100, add=TRUE)