【问题标题】:Exporting plots to PDF from R将绘图从 R 导出为 PDF
【发布时间】:2015-08-25 21:16:39
【问题描述】:

我已经搜索了这个网站和其他网站以寻求答案,但似乎无法让代码的 PDF 部分正常工作,非常感谢您的帮助。

此代码运行良好,它循环并在 RStudio 输出中为每个行业创建图表:

   gg <- list()
   #make the plots, facet by client on each page - works well
   for (p in 1:length(df)){
   gg[[p]] <- ggplot(data = df[[p]],  aes(x = MonthsActive, y = Participation, color = CommClient)) + 
      ylim(0,1) + geom_line(size = 0.8) + 
      scale_x_continuous(limits = c(1,13)) + 
      facet_wrap(~ClientName, scales="fixed") + 
      scale_color_hue(l = 45) + 
      ggtitle(sprintf("Participation Rate for %s for First Year",params[p]))
    plot(gg[[p]])
    } 

现在,当我将 PDF 函数包裹起来时,我无法让它输出绘图。我已经测试了目标路径(Windows 系统),打印时看起来还不错。有一次,我得到了空白的不可读的 PDF,因此该路径似乎有效。此代码不会创建单独的 PDF:

 gg <- list()
 #make the plots, facet by client on each page
  for (p in 1:length(df)){

 #set the file path by name - when using print looks fine

    myPath <- file.path("Q:","DataScience", "ParticipationPlots", paste(params[p], ".pdf", sep="")) 

    #set pdf as device and make individual PDFs

    pdf(file = myPath, onefile = F, paper = "USr", width = 11, height = 8.5)

    #this code is the same as above that works except for dev.off() at end
    gg[[p]] <- ggplot(data = df[[p]],  aes(x = MonthsActive, y = Participation, color = CommClient)) + 
      ylim(0,1) + geom_line(size = 0.8) + 
      scale_x_continuous(limits = c(1,13)) + 
      facet_wrap(~ClientName, scales="fixed") + 
      scale_color_hue(l = 45) + 
      ggtitle(sprintf("Participation Rate for %s for First Year",params[p]))
    plot(gg[[p]])
    }
 dev.off()

【问题讨论】:

  • 尝试使用ggsave 保存生成的绘图,使用 IMO 时更简洁。
  • 你应该使用print 而不是plot 用于网格图形cran.r-project.org/doc/FAQ/…

标签: r pdf plot ggplot2


【解决方案1】:

dev.off() 需要在循环内

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    • 2017-03-09
    • 2020-05-26
    • 2015-09-13
    相关资源
    最近更新 更多