Home > Software engineering >  How to draw two curves in one plot / graph
How to draw two curves in one plot / graph

Time:11-30

I have two functions, with a range-specific argument. I can’t get them on one chart in any way.

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)

I just started to learn this language, and I do not quite understand how this process can be performed.

If I execute the code, I get the following:

enter image description here enter image description here

I need these curves to be on the same graph

CodePudding user response:

You can try the lines() argument to add to an existing 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")

Giving you this:

enter image description here

CodePudding user response:

You can use ggplot2 and stat_function to draw multiple functions and to restrict the range of each of them:

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)

Output

You wan still add ylim (as I did) and xlim to restrict the main panel range, but the inside-functions xlim will restrict the computation of the functions to theses ranges

CodePudding user response:

Using curve might be quite efficient.

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

enter image description here

CodePudding user response:

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")

  •  Tags:  
  • r
  • Related