14

I have a simple problem in the plot function of R programming language. I want to draw a line between the points (see this link and how to plot in R), however, what I am getting something weird. I want only one point is connected with another point, so that I can see the function in a continuous fashion, however, in my plot points are connected randomly some other points. Please see the second plot.

Below is the code:

x <- runif(100, -1,1) # inputs: uniformly distributed [-1,1]
noise <- rnorm(length(x), 0, 0.2) # normally distributed noise (mean=0, sd=0.2)
f_x <- 8*x^4 - 10*x^2 + x - 4  # f(x), signal without noise
y <- f_x + noise # signal with noise

# plots 
x11()
# plot of noisy data (y)
plot(x, y, xlim=range(x), ylim=range(y), xlab="x", ylab="y", 
     main = "observed noisy data", pch=16)

x11()
# plot of noiseless data (f_x)
plot(x, f_x, xlim=range(x), ylim=range(f_x), xlab="x", ylab="y", 
     main = "noise-less data",pch=16)
lines(x, f_x, xlim=range(x), ylim=range(f_x), pch=16)

# NOTE: I have also tried this (type="l" is supposed to create lines between the points in the right order), but also not working: 
plot(x, f_x, xlim=range(x), ylim=range(f_x), xlab="x", ylab="y", 
     main = "noise-less data", pch=16, type="l")

First plot is correct: enter image description here While second is not what I want, I want a continuous plot: enter image description here

Community
  • 1
  • 1
Sanchit
  • 3,180
  • 8
  • 37
  • 53
  • 1
    See also [Plot, lines and disordered x and y](http://r.789695.n4.nabble.com/Plot-lines-and-disordered-x-and-y-td880487.html) – Henrik Nov 14 '15 at 11:55

1 Answers1

26

You have to sort the x values:

plot(x, f_x, xlim=range(x), ylim=range(f_x), xlab="x", ylab="y", 
     main = "noise-less data",pch=16)
lines(x[order(x)], f_x[order(x)], xlim=range(x), ylim=range(f_x), pch=16)

enter image description here

rcs
  • 67,191
  • 22
  • 172
  • 153
  • Hi, Thanks a lot. Can you please explain why the values of "x" and "f_x" need to be sorted? – Sanchit Nov 13 '15 at 19:28
  • 3
    Because you need a monotonuous increase of the x-values to draw the graph. – rcs Nov 13 '15 at 19:35
  • 2
    if you modify the first line `x <- sort(runif(100, -1,1))` your plot statements from the question will also work. – rcs Nov 13 '15 at 19:40
  • Yes, that makes sense. But, I thought x should already contains the monotonous incremented values or it should be handled by the plot function. Good to know. I am very new in R. Thanks. – Sanchit Nov 13 '15 at 19:49
  • `plot` can put points in any order - if it automatically sorted it would be impossible to draw a graph like yours. And `x` clearly isn't sorted already - it was a random draw! If 100 random points come out sorted you should worry about the random number generator! – Gregor Thomas Nov 13 '15 at 19:53