【问题标题】:Add multiple pre-made figures via for loop when using knitr使用knitr时通过for循环添加多个预制图形
【发布时间】:2013-12-30 15:16:47
【问题描述】:

我有几个预制图形,我想将它们添加到我正在使用 knitr 准备的乳胶文档中。

使用 for 循环之类的方法添加它们的最佳策略是什么?

非常感谢!

【问题讨论】:

  • 这是一个 LaTeX 文档。

标签: r knitr


【解决方案1】:

我的建议是构建一个数据框来支持有关所需 LaTeX 图形环境的元数据,然后使用 mapply 和自定义函数来构建所需的输出。这是一个示例 .Rnw 文件

\documentclass{article}
\usepackage{hyperref,fullpage}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,      
    urlcolor=cyan,
  }


\begin{document}
Thanks to \url{https://classroomclipart.com} for the graphics.

For displaying several pre-made figures you could write out the figure
environments yourself.

\begin{figure}[!h]
  \centering
  \caption{Explicit figure environment. \label{fig:00}}
  \includegraphics[width=0.2\linewidth]{figs/man-working-on-a-computer-clipart-318.jpg}
\end{figure}

To create many figure environments, I would suggest building a data.frame with
captions, figure labels, options, and file paths:

<<>>=
myfigs <-
  data.frame(caption = c("Bright Red Fall Foliage", "Chat 9", "Man On Computer"),
             label   = c("brff", "c9", "moc"),
             option  = c("width=0.1\\linewidth", "width=0.2\\linewidth", "width=0.3\\linewidth"),
             path    = c("figs/bright-red-fall-foliage-photo_8304-Edit.jpg",
                         "figs/chat-9-94.jpg",
                         "figs/man-working-on-a-computer-clipart-318.jpg"),
             stringsAsFactors = FALSE)

myfigs
@

Build a function for creating a figure environment:

<<>>=
build_fig_env <- function(caption = "", label = "", option = "", path = "") {
  cat(
  sprintf("\\begin{figure}[!h]\n\\centering\n\\caption{%s \\label{fig:%s}}\n\\includegraphics[%s]{%s}\n\\end{figure}\n\n\n",
          caption, label, option, path)
  )
}
@

Now call the function using mapply.  The mapply call is wrapped in a call to
invisible to suppress the irrelevant output.

<<results = "asis">>=
invisible(
          mapply(build_fig_env,
                 caption  = myfigs$caption,
                 label    = myfigs$label,
                 option   = myfigs$option,
                 path     = myfigs$path,
                 SIMPLIFY = FALSE)
)
@

This is just one solution to your question.  

\end{document}

输出如下:

或者你可以查看pdf here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多