2017-09-01 190 views
1

我试图在同一个图表上绘制两个函数(即2x + 1和3x - 0.5 * x^2)的图形,但有两个不同的范围(x < = 3和x> 3)。到目前为止,我已经定义了两个功能如下:在R中绘制两个函数的图形

# Define first function with given range 
Line1 <- function(x) { 
    if (x <= 3) { 
     (3*x) + 1 } else { 
    }  
} 

# Define second function with given range 
Line2 <- function(x) { 
    if (x > 3) { 
     2*x - (0.5*(x^2)) } else { 
    }   
} 

# Plot functions 
ggplot(d,aes(x=x)) + stat_function(fun=rwrap(Line1,0,3),geom="line",col="blue") 
+ stat_function(fun=rwrap(Line2,3,5),geom="line",col="red")` 

当我运行代码,我收到以下错误信息:

Error: Discrete value supplied to continuous scale In addition:

Warning messages:
1: In if (x <= 3) { : the condition has length > 1 and only the first element will be used
2: In if (x > 3) { : the condition has length > 1 and only the first element will be used

我试图解决它,但我只是失去了在此刻。

+0

为什么你的代码引用? – Gregor

+3

问题是你的函数没有被矢量化。他们一次只能处理一个'x'值,但'Line1(0:10)'不起作用。使用'ifelse'作为单个函数作为if的向量化版本{if else else} {:foo = function(x)ifelse(x <= 3,3 x + 1,2 * x - 0.5 * x^2)'。 – Gregor

+0

对不起引用,我犯了一个复制和粘贴过程的错误。我明白你的陈述。但是,我将如何绘制不同颜色的线? – user8550070

回答

0

的问题是,你的功能没有量化。他们会为x在一个单一的价值在工作时间,但Line1(0:10)将无法​​正常工作。

使其与ifelse一个量化的功能,向量化版本的if{}else{}

foo = function(x) { 
    ifelse(x <= 3, 3 * x + 1, 2 * x - 0.5 * x^2) 
} 

你可以打破它,就像这样:

bar = function(x) 3 * x + 1 
baz = function(x) 2 * x - 0.5 * x^2 
foo = function(x) ifelse(x <= 3, bar(x), baz(x)) 

虽然你当然会想使用更多有意义的名字比这些占位符。