Custom output hooks in knitr

2019-07-15 10:05发布

I am trying to create a chunk hook that can produce a \floatfoot{} as part of the output from a chunk.

Hopefully the following example makes clear what I am trying to achieve:

1. .Rnw file

Here is the knitr file.

\documentclass[a4paper]{article}
\title{Learn Moar knitr!}
\author{Foo Bar}
\date{\today}

\usepackage{blindtext}
\usepackage{floatrow}
\begin{document}
\blindtext

<<label=plotWithNotes, fig.lp='fig:', fig.cap='This is a figure'>>=
plot(rnorm(100), rbinom(n = 100, size = 1, prob = 0.5))
@

\end{document}

2. LaTeX chunk

\begin{figure}[]
\includegraphics[width=\maxwidth]{figure/plotWithNotes} \caption[This is a figure]{This is a figure\label{fig:plotWithNotes}}
\end{figure}

3. floatfoot

The markup \floatfoot{} provided by the floatrow package produces a footnote to the graph, and to show its use, I modify the LaTeX chunk above.

\begin{figure}[]
\includegraphics[width=\maxwidth]{figure/plotWithNotes} \caption[This is a figure]{This is a figure\label{fig:plotWithNotes}}
\floatfoot{\emph{Note:} This is a footer to the plot and contains some information about the plot.}
\end{figure}

Is there any way I can generate the text inside floatfoot above using a chunk option?

I made a start on writing such a function, but can't get it to work:

<<echo = TRUE, include = FALSE>>=
fnOutHookInsertFoot = function(x = NULL, options = NULL) {
  # find the location of the \end{figure}
  gsub('\\end{figure}', '\\floatfoot{Some text.}\\end{figure}', 
       x, fixed = TRUE)

}
# fnOutHookInsertFoot()
knit_hooks$set(plot = fnOutHookInsertFoot)
@

0条回答
登录 后发表回答