R:使用我自己的公式将曲线添加到x,y散点图中

use*_*839 5 curve r scatter-plot ggplot2

我想在x,y散点图中添加具有以下等式的曲线:y < - (105 + 0.043(x ^ 2-54x)).是否可以在plot()函数中使用?另外,如果我使用qplot代替(ggplot2)有没有办法绘制这条曲线?

Gre*_*gor 7

# data for scatterplot
x = rnorm(10, sd = 10)
y = (105 + 0.043 * (x^2 - 54 * x)) + rnorm(10, sd = 5)
Run Code Online (Sandbox Code Playgroud)

基础绘图

plot(x, y)
curve(105 + 0.043 * (x^2 - 54 * x), add = T)
Run Code Online (Sandbox Code Playgroud)

对于ggplot,我们需要一个data.frame

dat = data.frame(x = x, y = y)

ggplot(dat, aes(x , y)) + 
    geom_point() +
    stat_function(fun = function(x) 105 + 0.043 * (x^2 - 54 * x))
Run Code Online (Sandbox Code Playgroud)

  • 你也可以做`qplot(...)+ stat_function(...)`. (2认同)