我试图在同一个图表上绘制两个函数(即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
我试图解决它,但我只是失去了在此刻。
为什么你的代码引用? – Gregor
问题是你的函数没有被矢量化。他们一次只能处理一个'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
对不起引用,我犯了一个复制和粘贴过程的错误。我明白你的陈述。但是,我将如何绘制不同颜色的线? – user8550070