Inside the plot generated in a chunk in a knitr/LaTeX document I want to position a text string with a reference to a particular figure elsehwere in the document, something like "See Fig. 10", based on the label of a that particular figure, lets say "fig:sim1". So I wrote the following R function which reads the .aux file of the LaTeX-document I'm writing and extracts the counter of the figure matching a specific label
ref <- function(label) {
lines <- scan("mismatch-final.aux","character",sep="\n")
line <- grep(paste("\\{",label,"\\}",sep=""),lines,value=TRUE)
strsplit(strsplit(line,"\\{\\{")[[1]][2],"\\}\\{")[[1]][1]
}
I can then generate the desired text string from within the chunk and place it inside the plot with something like
text(5,10,paste("See Fig.~",ref("fig:sim1")))
This should work but perhaps there is a cleaner way of doing this? Also, is there a way to get at the .aux filename from within the chunk such that the ref function above would be made more general?
Another way to do that is to use the tikzDevice package and TikZ plots, so you can write raw LaTeX expressions in your plot, e.g
\begin{figure}
....
\caption{Simulation of something. \label{fig:sim1}}
\end{figure}
<<test, dev='tikz', external=FALSE>>=
plot(rnorm(10), rnorm(10))
text(0, 0, 'See Fig \\ref{fig:sim1}')
@
Depending on the complexity of your plot, this chunk may take a few seconds to compile each time. The plot is saved as a LaTeX file, and any LaTeX commands will work in it.