在R中绘制大量的线条

时间:2015-03-26 08:05:39

标签: r

我编写了一个代码,根据不同的条件在不同颜色的图表中绘制近100000行。代码如下。

for(i in c(160000:260000)){
  if(data[i,]$Char1 == 'A' & data[i,]$Char2 == 'S'){
    if(data[i,]$Q1 < data[i,]$Q2){
      lines(c(i,i),c(data[i,]$P + 2,data[i,]$P + 22),col="green")
    }else{
      lines(c(i,i),c(data[i,]$P - 2,data[i,]$P - 22),col="green")
    }
  }
  if(data[i,]$Char1 == "B" & data[i,]$Char2 == 'S'){
    lines(c(i,i),c(data[i,]$P + 2,data[i,]$P + 22),col='blue')
  }
}

之前我已绘制了一张普通图表。这是

plot(data$P,type="l")

我运行了代码并持续了2-3个多小时,它一直在运行,直到我停止它为止。有没有办法轻松地用更少的时间完成这项任务?

2 个答案:

答案 0 :(得分:5)

您可以通过不实际显示绘图来节省一些计算时间。正在运行

library(scales)
n <- 100000
m <- 20

system.time({
  plot(0, 0, type = 'n', xlim = c(0, 10), ylim = c(0, 10), xlab = '', ylab = '')
  for (i in 1:n) lines(sort(runif(m, max = 10)), sort(runif(m, max = 10)), 
                       col = ifelse(i %% 10 == 0, 'red', alpha('lightblue', 0.1)), 
                       lwd = 0.2)
})

VS

system.time({
  png('plot.png')
  plot(0, 0, type = 'n', xlim = c(0, 10), ylim = c(0, 10), xlab = '', ylab = '')
  for (i in 1:n) lines(sort(runif(m, max = 10)), sort(runif(m, max = 10)), 
                       col = ifelse(i %% 10 == 0, 'red', alpha('lightblue', 0.1)), 
                       lwd = 0.2)
  dev.off()
})

给出

  user  system elapsed 
44.415   0.704  45.435 

VS

  user  system elapsed 
23.115   0.294  23.585 

在我的机器上。 result

<强>更新

使用CathG的答案会在绘制线条时大幅缩短计算时间:

n <- 100000
data <- data.frame(x0 = runif(n), y0 = runif(n), x1 = runif(n), 
                   y1 = runif(n), col = 1:10)

system.time({
  png('plot.png', 640, 640)
  plot(0, 0, type = 'n', xlab = '', ylab = '', xlim = c(0, 1), ylim = c(0, 1))
  for (i in 1:n) lines(data[i, c(1, 3)], data[i, c(2, 4)], col = data$col, 
                       lwd = 0.1)
  dev.off()
})

system.time({
  png('plot.png', 640, 640)
  plot(0, 0, type = 'n', xlab = '', ylab = '', xlim = c(0, 1), ylim = c(0, 1))
  segments(data$x0, data$y0, data$x1, data$y1, col = data$col, lwd = 0.1)
  dev.off()
})

给出

   user  system elapsed 
119.682   0.822 121.525 

VS

 user  system elapsed 
2.267   0.020   2.303 

答案 1 :(得分:5)

我认为您应首先计算不同的xy(以及color),然后使用segments在一次调用中将它们全部绘制出来并且我认为您应该例如,使用png直接绘制它们,而不是在窗口设备中绘制:

data2 <- data[160000:260000, ]

data2$x0 <- data2$x1 <- 160000:260000

cond1 <- (data2$Char1=="A") & (data2$Char2 == "S") & (data2$Q1 < data2$Q2)
cond2 <- (data2$Char1=="A") & (data2$Char2 == "S") & (data2$Q1 >= data2$Q2)
cond3 <- (data2$Char1=="B") & (data2$Char2 == "S")

data2$y0[cond1] <- data2$P[cond1] + 2
data2$y0[cond2] <- data2$P[cond2] - 2
data2$y0[cond3] <- data2$P[cond3] + 2

data2$y1[cond1] <- data2$P[cond1] + 22
data2$y1[cond2] <- data2$P[cond2] - 22
data2$y1[cond3] <- data2$P[cond3] + 22

data2$color[cond1] <- "green"
data2$color[cond2] <- "green"
data2$color[cond3] <- "blue"

png("nameofyourfile.png")
plot(data$P,type="l")
segments(data2$x0, data2$y0, data2$x1, data2$y1, col=data2$color)
dev.off()