我試圖在同一個圖表上繪製兩個函數(即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