在R中将函数绘制在数据点之上

9
有没有一种使用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 #?

在这种情况下,我的数据是使用函数生成的,但我想了解如何在ggplot中使用curve()
2个回答

16

你可能想要使用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")

3
鉴于您的问题标题为“在R中绘制函数”,以下是如何使用curve将函数添加到基本R图形的方法。
按照先前的方式创建数据。
eq = function(x){x*x}; x = (1:50); y = eq(x)

然后使用基本图形中的plot来绘制点,接着使用带有add=TRUE参数的curve来添加曲线。

plot(x, y,  xlab = "X-axis", ylab = "Y-axis") 
curve(eq, add=TRUE)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接