[英]How to draw two curves in one plot / graph
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:您可以尝试将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")
Giving you this:给你这个:
You can use ggplot2
and stat_function
to draw multiple functions and to restrict the range of each of them:您可以使用ggplot2
和stat_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)
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您仍然要添加ylim
(就像我一样)和xlim
来限制主面板范围,但是内部函数xlim
会将函数的计算限制在这些范围内
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.