r - 在R中的数据点之上绘制函数

标签 r function statistics plot ggplot2

有没有一种方法可以使用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()

最佳答案

您可能想要 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 - 在R中的数据点之上绘制函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1853703/

相关文章:

statistics - logit 模型中的尺度参数

R:setdiff 的非贪婪版本?

r - Boxplot 上的全文标签,添加了平均点

mysql - R:Windows 上的 MySQL 字符编码

variables - R函数中的全局变量

r - 对表中的多个变量应用 t 检验和 Wilcoxon 检验

r - 之间的区别和||在 R

javascript - 未捕获的 ReferenceError : function is not defined at HTMLInputElement. onclick

JavaScript:找到最大间隔重叠的点

python - 将对数正态分布的拟合 PDF 缩放为 python 中的直方图