I always wondered how such pictures are made:
I am working with the R programming language. I would like to plot a parabola with "random noise" added to the parabola. I tried something like this:
x = 1:100
y = x^2
z = y rnorm(1, 100,100)
plot(x,z)
But this is still producing a parabola without "noise".
Can someone please show me how I can add "noise" to a parabola (or any function) in R?
Thanks!
CodePudding user response:
In this case you need to generate 100 random points or will be adding the same amount of noise to each point (thus no noise). z = y rnorm(100, 100,100)
x = 1:100
y = x^2
z = y rnorm(length(y), 100,100)
plot(x,z)
CodePudding user response:
In your code you add the same value to all your points so it just shifts your curve up by that constant. Instead you need to generate a vector of random noise the same length as your y
variable. Also you probably want to set the mean = 0
for the rnorm()
noise so that it's truly random noise around the true value not systematically 100
units larger.
To get something very similar to your example, you can overplot the second vector with noise using lines()
and add a legend with the code below.
x = 1:100
y1 = x^2
y2 = y1 rnorm(100, 0, 500)
plot(x, y1, type = "l", ylab = "y")
lines(x,y2,type = "l", col = "red")
legend(
x = "top",
legend = c("y1", "y2"),
col = c("black", "red"),
lwd = 1,
bty = "n",
horiz = T
)
Created on 2022-11-08 with reprex v2.0.2