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 #?

在这种情况下,我的数据是使用该函数生成的,但我想了解如何curve()与 ggplot 一起使用。

4

2 回答 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")
于 2009-12-05T23:35:09.193 回答
3

鉴于您的问题标题是“在 R 中绘制函数”,以下是如何使用curve将函数添加到基本 R 图。

像以前一样创建数据

eq = function(x){x*x}; x = (1:50); y = eq(x)

然后使用plotfrom base graphics 绘制点,然后curve使用add=TRUE参数添加曲线。

plot(x, y,  xlab = "X-axis", ylab = "Y-axis") 
curve(eq, add=TRUE)
于 2012-08-02T23:40:17.310 回答