使用R脚本生成PDF时出现错误

3
我正在使用R循环遍历数据框的列,并制作分析结果的图表。脚本运行时没有出现任何错误,但生成的pdf文件无法打开。
如果我运行脚本内容,它就可以正常工作。我想知道是否存在快速循环的问题,所以我尝试强制让它暂停。但这似乎没有什么区别。我对人们提出的任何建议都很感兴趣,我也是R的新手,欢迎提出改进方法。谢谢。
for (i in 2:22) {

  # Organise data
  pop_den_z = subset(pop_den, pop_den[i] != "0")  # Remove zeros
  y = pop_den_z[,i]        # Get y col
  x = pop_den_z[,1]        # get x col
  y = log(y)               # Log transform

  # Regression
  lm.0 = lm(formula = y ~ x)                # make linear model
  inter = summary(lm.0)$coefficients[1,1]   # Get intercept
  slop = summary(lm.0)$coefficients[2,1]    # Get slope

  # Write to File
  a = c(i, inter, slop)
  write(a, file = "C:/pop_den_coef.txt", ncolumns = 3, append = TRUE, sep = ",")

  ## Setup pdf
  string = paste("C:/LEED/results/Images/R_graphs/Pop_den", paste(i-2), "City.pdf")
  pdf(string, height = 6, width = 9)

  p <- qplot(
    x, y,
    xlab = "Radius [km]",
    ylab = "Population Density [log(people/km)]",
    xlim = x_range,
    main = "Analysis of Cities"
  )

  # geom_abline(intercept,slope)
  p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1)

  Sys.sleep(5)

  ### close the PDF file
  dev.off()
}
1个回答

10
该行应该是:

print(p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1))

在PDF设备中,ggplot(和lattice)只有在显式打印时才会写入文件。


这只涉及到Lattice和ggplot2,与Grid没有太大关系。 - hadley
谢谢,那个方法可行。我没意识到需要显式地打印输出。 - womble

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