以pdf和png格式保存图形,但在最终文档中使用pdf文件 [英] Saving graphs in both pdf and png format but using pdf files in the final document

查看:136
本文介绍了以pdf和png格式保存图形,但在最终文档中使用pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用knitr进行分析.我可以用\SweaveOpts{dev=pdf}用pdf格式保存图形,而用\SweaveOpts{dev=png}用png格式保存图形.我有兴趣一次运行以pdf和png格式保存图形,但希望在最终文档中以交互方式使用pdf.任何建议将不胜感激.谢谢

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

推荐答案

以下是真正的解决方案:

Here comes the real solution:

Knitr 0.3.9 开始为每个块支持多个设备(目前,您必须从GitHub);根据您的情况,您可以将块选项dev=c('pdf', 'png')设置为同时获取PDF和PNG文件.

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.

这是一个使用ImageMagick将PDF文件转换为PNG的解决方案.当然,您必须首先安装ImageMagick,并确保其bin目录位于PATH中:

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
})

基本上,此挂钩是在一个块之后执行的,并在所有PDF图形上运行convert foo.pdf foo.png.您可以像这样使用它

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)
@

或者如果将所有图形放在单独的目录中,则可以直接在该目录中运行convert(即不必在R中调用system()).

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).

这不是理想的解决方案,但应该可以.要使用R的本机png()设备,您需要首先在上面的评论中回答我的问题.

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.

这篇关于以pdf和png格式保存图形,但在最终文档中使用pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆