pdf - 使用 R 中的脚本生成 pdf 时出错

标签 pdf r statistics graph

我正在使用 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()
}

最佳答案

该行应该是

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

在 pdf 设备中,ggplot(和 lattice)仅在显式打印时写入文件。

关于pdf - 使用 R 中的脚本生成 pdf 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797712/

相关文章:

Java - 读取和写入在浏览器窗口内呈现的 Pdf

javascript - 使用jspdf将html页面保存为pdf,如果浏览器缩放,保存的pdf页面内容不完整,为什么?

pdf - Pandoc MD到PDF,全尺寸水平尺

r - 有因素时的多重共线性检验

math - 在不失去一致性的情况下将数据从 double 映射到整数的最简单方法

database - 是否可以根据退出/进入数量的数据估计平均访问者持续时间?

python - scipy.stats.chi2_contingency 生成的 p 值用于独立性测试

javascript - 从 HTML 中的其他域渲染 pdf

r - 如何用R中的行均值估算缺失值

r - 如何处理对数图中的零