Saving graphs in both pdf and png format but using pdf files in the final document

不打扰是莪最后的温柔 提交于 2019-12-08 02:51:00

问题


I'm using knitr for my analysis. I can save graphs in pdf format with \SweaveOpts{dev=pdf} and in png format with \SweaveOpts{dev=png}. I'm interested to save graphs both in pdf and png format in one run but to use the pdf in the final documents interactively. Any suggestion will be highly appreciated. Thanks


回答1:


Here comes the real solution:

Knitr 0.3.9 starts to support multiple devices per chunk (for now, you have to install from GitHub); in your case, you can set the chunk option dev=c('pdf', 'png') to get both PDF and PNG files.


Here is a solution that uses ImageMagick to convert PDF files to PNG. Of course you have to install ImageMagick first, and make sure its bin directory is in PATH:

knit_hooks$set(convert = function(before, options, envir) {
  # quit if before a chunk or no figures in this chunk
  if (before || (n <- options$fig.num) == 0L) return()
  # only convert pdf files
  if (options$fig.ext != 'pdf') return()

  # use ImageMagick to convert all pdf to png
  name = fig_path()  # figure filename
  owd = setwd(dirname(name)); on.exit(setwd(owd))
  files = paste(basename(name), if (n == 1L) '' else seq(n), sep = '')
  lapply(files, function(f) {
    system(sprintf('convert %s.pdf %s.png', f, f))
  })
  NULL
})

Basically this hook is executed after a chunk and run convert foo.pdf foo.png on all PDF figures. You can use it like

<<test-png, convert=TRUE>>=
  plot(1); plot(2)
@

Or if you put all figures in a separate directory, you can run convert directly in that directory (i.e. do not have to call system() in R).

This is not an ideal solution but should work. To make use of R's native png() device, you need to answer my question in the above comment first.



来源:https://stackoverflow.com/questions/9659237/saving-graphs-in-both-pdf-and-png-format-but-using-pdf-files-in-the-final-docume

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!