【问题标题】:Line connecting the points in the plot function in R [duplicate]连接R中绘图函数中的点的线[重复]
【发布时间】:2016-02-15 11:22:36
【问题描述】:

我在 R 编程语言的绘图功能中有一个简单的问题。我想在两点之间画一条线(see this linkhow to plot in 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")

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

【问题讨论】:

标签: r plot


【解决方案1】:

您必须对 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”的值需要排序吗?
  • 因为您需要单调增加 x 值来绘制图形。
  • 如果您修改第一行x &lt;- sort(runif(100, -1,1)),您的问题中的情节陈述也将起作用。
  • 是的,这是有道理的。但是,我认为 x 应该已经包含单调递增的值,或者它应该由 plot 函数处理。很高兴知道。我在R.谢谢。 span>
  • plot 可以按任何顺序排列点 - 如果它自动排序,就不可能画出像你这样的图表。和x显然没有排序 - 这是一个随机的绘图!如果 100 个随机点排序出来,你应该担心随机数生成器!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多