0

I want to add a random curve to a plot to test whats fitting best to my data.

df <- data.frame(a = c(-1.973, -1.685, 2.050, 0.496, 3.310, 2.604, 1.477, 5.552, 2.039, 1.503, 2.171, 1.095),
                 b = c(21,27,36,36,66,53,40,40,65,39,37,32))
lm(b~a,data = df)plot(df$a, df$b, xlab = "a", ylab = "b")
x<-lm(df$b~df$a)$coefficients[1]
curve(x+lm(df$b~df$a)$coefficients[2], add=TRUE, col="red")

Though this plot I can draw a regression line (picture) but can I also add a random curve?

enter image description here

When I run the code, I only see the curve and not the data. Camn anyone help what I have to do that the data and the curve is visible? Thanks...

Spektre
  • 49,595
  • 11
  • 110
  • 380
Niknue
  • 3
  • 2
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 04 '22 at 17:45

1 Answers1

0

I'm not sure exactly what you mean by "random curve". You seem to just be trying to plot the regression line. In this case, you can just use abline

reg <- lm(b~a,data = df)
plot(df$a, df$b, xlab = "a", ylab = "b")
abline(reg, col="red")

enter image description here Or if you really wanted to use curve(), the x variable is special and needs to be able to change. So it would be

curve(reg$coefficients[1] + x*reg$coefficients[2], add=TRUE, col="red")
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Okay. And is it possible to draw for example a curve x^2 or x^3, log, e^x, or something else (this is what I mean with "random" curve)? Or is it just possible to draw a linear relation? – Niknue Nov 04 '22 at 19:06
  • Sure, just put in whatever equation you want, but note that after you call `plot()`, the `x` and `y` limits will not change. So if your curve doesn't cross into the plot region, you won't see it. – MrFlick Nov 04 '22 at 19:28
  • Okay, then I think this is my problem. Thank you for your help! – Niknue Nov 04 '22 at 21:25