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:
I need these curves to be on the same graph
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:
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.