簡體   English   中英

如何在一條中繪制兩條曲線 plot / 圖

[英]How to draw two curves in one plot / graph

我有兩個函數,帶有一個特定於范圍的參數。 我無法以任何方式將它們放在一張圖表上。

f1 = function(x1){
  return (sqrt(64-x1^2))
  }

f2 = function(x2){
  return (cos(x2) - x2)
}

plot(f1,-5, 1) 
plot(f2,-pi/2, pi/2)

我剛開始學習這門語言,我不太明白這個過程是如何進行的。

如果我執行代碼,我會得到以下信息:

在此處輸入圖像描述 在此處輸入圖像描述

我需要這些曲線在同一張圖上

您可以嘗試將lines()參數添加到現有的 plot 中:

f1 = function(x1){
  return (sqrt(64-x1^2))
}

f2 = function(x2){
  return (cos(x2) - x2)
}


x <- c(-5:5) # choose your x value range here
y1 <- mapply(FUN = f1,x1 = x) # lets get the y values before plotting
y2 <- mapply(FUN = f2,x2 = x) # lets get the y values before plotting


plot(x,y1, type = "l", col = "red", ylim = c(-5,10))
lines(x, y2, col = "blue", type = "l")

給你這個:

在此處輸入圖像描述

您可以使用ggplot2stat_function來繪制多個函數並限制每個函數的范圍:

library(ggplot2)
ggplot() +
  stat_function(fun = function(x) cos(x) - x, color = "red", xlim = c(-pi/2,pi/2)) +
  stat_function(fun = function(x) sqrt(64-x^2), xlim = c(-5,1)) +
  ylim(-10,10)

輸出

您仍然要添加ylim (就像我一樣)和xlim來限制主面板范圍,但是內部函數xlim會將函數的計算限制在這些范圍內

使用curve可能非常有效。

curve(sqrt(64 - x^2), col=2, xlim=c(-5, 1), ylim=c(-5, 10))
curve(cos(x) - x, col=4, add=TRUE)

在此處輸入圖像描述

f1 = function(x1){
    return (sqrt(64-x1^2))
}

f2 = function(x2){
    return (cos(x2) - x2)
}

x = seq(-5, 1, len=20)
y = cbind(y1=f1(x), y2=f2(x))

matplot(x, y, col=1:2, type="l", lty=1)
legend('topright', legend=c(expression(f[1]), expression(f[2])), col = 1:2, lty=1, bty = "n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM