连接 R 中绘图函数中的点的线

问题描述 投票:0回答:1

我在R编程语言的绘图函数中遇到一个简单的问题。我想在点之间画一条线(参见此链接如何在 R 中绘制),但是,我得到了一些奇怪的东西。我希望只有一个点与另一点连接,以便我可以以连续的方式看到该函数,但是,在我的绘图中,点是随机连接的一些其他点。请看第二个情节。

以下是代码:

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")

第一个情节是正确的:enter image description here 虽然第二不是我想要的,但我想要一个连续的情节:enter image description here

r plot
1个回答
27
投票

您必须对 x 值进行排序:

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

© www.soinside.com 2019 - 2024. All rights reserved.