是否有使用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从基地图形绘制点,随后curveadd=TRUE参数,添加的曲线。

plot(x, y,  xlab = "X-axis", ylab = "Y-axis") 
curve(eq, add=TRUE)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top