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: While second is not what I want, I want a continuous plot:
A connected scatter plot represents the relationship between two variables, generally through the time. You can create this type of chart in base R with the plot function, setting type = "b" . The symbol used by default when type = "b" can be modified making use of the pch argument.
segment() function in R Language is used to draw a line segment between to particular points. Parameters: x, y: coordinates to draw a line segment between provided points. Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment .
lines() function in R Programming Language is used to add lines of different types, colors and width to an existing plot. Parameters: x, y: Vector of coordinates. col: Color of line.
To add new points to an existing plot, use the points() function. The points function has many similar arguments to the plot() function, like x (for the x-coordinates), y (for the y-coordinates), and parameters like col (border color), cex (point size), and pch (symbol type).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With