[英]Plotting functions on top of datapoints in R
有没有办法使用ggplot在数据上叠加数学函数?
## add ggplot2
library(ggplot2)
# function
eq = function(x){x*x}
# Data
x = (1:50)
y = eq(x)
# Make plot object
p = qplot(
x, y,
xlab = "X-axis",
ylab = "Y-axis",
)
# Plot Equation
c = curve(eq)
# Combine data and function
p + c #?
在这种情况下,我的数据是使用函数生成的,但我想了解如何将curve()
与ggplot一起使用。
你可能想要stat_function
:
library("ggplot2")
eq <- function(x) {x*x}
tmp <- data.frame(x=1:50, y=eq(1:50))
# Make plot object
p <- qplot(x, y, data=tmp, xlab="X-axis", ylab="Y-axis")
c <- stat_function(fun=eq)
print(p + c)
如果你真的想使用curve()
,即计算的x和y坐标:
qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
鉴于您的问题标题是“在R中绘制函数”,这里是如何使用curve
将函数添加到基础R图。
像以前一样创建数据
eq = function(x){x*x}; x = (1:50); y = eq(x)
然后使用plot
从基地图形绘制点,随后curve
与add=TRUE
参数,添加的曲线。
plot(x, y, xlab = "X-axis", ylab = "Y-axis")
curve(eq, add=TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.