[英]How to plot a function curve in R
为类似的函数绘制简单曲线的替代方法是什么
eq = function(x){x*x}
在 R?
这听起来很明显的问题,但我只能在stackoverflow上找到这些相关问题,但它们都更具体
我希望我没有写重复的问题。
我在网上做了一些搜索,这是我找到的一些方法:
最简单的方法是使用没有预定义函数的曲线
curve(x^2, from=1, to=50, , xlab="x", ylab="y")
当你有一个预定义的函数时,你也可以使用曲线
eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")
如果你想使用 ggplot,
library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) +
stat_function(fun=eq)
你的意思是这样吗?
> eq = function(x){x*x}
> plot(eq(1:1000), type='l')
(或与您的功能相关的任何值范围)
plot
有一个plot.function
方法
plot(eq, 1, 1000)
或者
curve(eq, 1, 1000)
这是一个格子版本:
library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")
具有我需要的其他设置的格子解决方案:
library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
X<-seq(0,10,0.00001)
col = rgb(红色 = 255,绿色 = 90,蓝色 = 0,maxColorValue = 255)
lwd = 2
cex.lab = 3.5,cex.axis = 3.5
正如 sjdh 也提到的,ggplot2 来救援。 不制作虚拟数据集的更直观的方法是使用 xlim:
library(ggplot2)
eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)
此外,对于更平滑的图,我们可以使用 n 设置图插值的点数:
base + geom_function(fun=eq, n=10000)
我有一个函数( emax()
),涉及 3 个参数(a、b 和 h),我想绘制它的线:
emax = function(x, a, b, h){
(a * x^h)/(b + x^h)
}
curve(emax, from = 1, to = 40, n=40 a = 1, b = 2, h = 3)
Error in emax(x) : argument "a" is missing, with no default error
。
通过使用以下语法将命名参数放入函数中来解决此问题:
curve(emax(x, a = 1, b = 2, h = 3), from = 1, to = 40, n = 40)
这与编写curve(expr, from, to, n, ...)而不是curve(expr(x,...), from, to, n)的文档相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.