在R中的plot函数中,连接点的线。

14

我在R编程语言的plot函数中遇到了一个简单的问题。我想要在点之间绘制一条线(参见此链接如何在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")

第一个图是正确的:输入图片描述 而第二个图并不是我想要的,我想要一个连续的图:输入图片描述


1个回答

26

你需要对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)

输入图像描述


嗨,非常感谢。您可以解释一下为什么需要对“x”和“f_x”的值进行排序吗? - Sanchit
3
因为需要保证 x 值单调递增才能绘制出图形。 - rcs
2
如果您修改第一行 x <- sort(runif(100, -1,1)),那么您在问题中的绘图语句也将能够正常工作。 - rcs
是的,那很有道理。但是,我认为x应该已经包含了单调递增的值,或者应该由绘图函数处理。好的,我知道了。我在R方面非常新手。谢谢。 - Sanchit
“plot” 可以按任意顺序放置点 - 如果它自动排序,将无法绘制像您的图表一样的图形。而且,“x” 明显还没有排序 - 这是一个随机抽取!如果 100 个随机点出现排序,那么您应该担心随机数生成器! - Gregor Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接