繁体   English   中英

如何在R中的绘图上画线?

[英]How to draw lines on a plot in R?

我需要从存储在文本文件中的数据绘制线条。 到目前为止,我只能在图形上绘制点,并且希望将它们作为线(线图)。

这是代码:

pupil_data <- read.table("C:/a1t_left_test.dat", header=T, sep="\t") 

max_y <- max(pupil_data$PupilLeft)

plot(NA,NA,xlim=c(0,length(pupil_data$PupilLeft)), ylim=c(2,max_y)); 

for (i in 1:(length(pupil_data$PupilLeft) - 1)) 
{
    points(i, y = pupil_data$PupilLeft[i], type = "o", col = "red", cex = 0.5, lwd = 2.0)
}

请帮助我更改以下代码行:

points(i, y = pupil_data$PupilLeft[i], type = "o", col = "red")

从数据画线。

这是文件中的数据:

PupilLeft  
3.553479    
3.539469    
3.527239    
3.613131    
3.649437    
3.632779    
3.614373    
3.605981    
3.595985    
3.630766    
3.590724    
3.626535    
3.62386 
3.619688    
3.595711    
3.627841    
3.623596    
3.650569    
3.64876 

默认情况下,R将绘制一个向量作为y坐标,并使用一个序列作为x坐标。 因此,要制作所需的图,您需要做的是:

plot(pupil_data$PupilLeft, type = "o")

您没有提供任何示例数据,但是可以通过内置的iris数据集看到它:

plot(iris[,1], type = "o")

实际上,这确实将点绘制为线。 如果您实际上得到的是没有线的点,则需要提供一个包含数据的示例,以找出原因。

编辑:

由于循环,您的原始代码无法正常工作。 您实际上是在要求R每次通过循环绘制一条将单个点连接到自身的线。 下次通过循环R时,您不知道还有其他要连接的点。 如果这样做的话,这将破坏points的预期用途,即在现有图上添加点/线。

当然,将点连接到自身的线没有任何意义,因此不会绘制(或绘制得太小而看不到,结果相同)。

您的示例最容易完成而没有循环:

PupilLeft <- c(3.553479 ,3.539469 ,3.527239 ,3.613131 ,3.649437 ,3.632779 ,3.614373
               ,3.605981 ,3.595985 ,3.630766 ,3.590724 ,3.626535 ,3.62386 ,3.619688
               ,3.595711 ,3.627841 ,3.623596 ,3.650569 ,3.64876)

plot(PupilLeft, type = 'o')

如果确实需要使用循环,那么编码会变得更加复杂。 一种方法是使用闭包:

makeaddpoint <- function(firstpoint){
  ## firstpoint is the y value of the first point in the series

  lastpt <- firstpoint
  lastptind <- 1

  addpoint <- function(nextpt, ...){
    pts <- rbind(c(lastptind, lastpt), c(lastptind + 1, nextpt))
    points(pts, ... )
    lastpt <<- nextpt
    lastptind <<- lastptind + 1
  }

  return(addpoint)

}

myaddpoint <- makeaddpoint(PupilLeft[1])

plot(NA,NA,xlim=c(0,length(PupilLeft)), ylim=c(2,max(PupilLeft)))

for (i in 2:(length(PupilLeft))) 
{
    myaddpoint(PupilLeft[i], type = "o")
}

然后,您可以使用需要进行的任何测试将myaddpoint调用包装在for循环中,以决定是否实际绘制该点。 makeaddpoint返回的makeaddpoint将为您跟踪makeaddpoint索引。

这是针对类似Lisp的语言的常规编程。 如果发现它令人困惑,则可以不关闭而执行此操作,但是您需要处理递增索引并“手动”在循环中存储先前的点值。

有经验的R编码人员强烈反对在不需要时使用for循环。 这是一个无循环使用名为segments的矢量化函数的示例,该函数采用4个矢量作为参数:x0,y0,x1,y1

npups <-length(pupil_data$PupilLeft)
segments(1:(npups-1), pupil_data$PupilLeft[-npups],  # the starting points
           2:npups, pupil_data$PupilLeft[-1] )        # the ending points

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM