TransWikia.com

latex - includegraphic with variables in the name

TeX - LaTeX Asked by John Sly on November 28, 2020

I’m no pro when it comes to latex and I’m working on something that’s already been a bit established. I have a batch that produces multiple pdfs with a latex/sweave template. I’m attempted to insert a graphic that has a variable in the name but I’m striking out bad. I’m hoping I can get some help cleaning it up.

The code I’m trying…

newpage
subsec{graphic page}
rptpage{ showtitle{} }
graphicsrc <- sprintf('name_with_underscores_%02d.pdf', objectnum)

includegraphics[width=paperwidth]{graphicsrc}
@

objectnum is a passed variable.

Everything works fine if I run the script with everything hard coded as such:

newpage
subsec{graphic page}
rptpage{ showtitle{} }
includegraphics[width=paperwidth]{name_with_underscores_01.pdf}
@

The problem is, I can’t hard code these to run them individually. I’m really hoping someone can help me debug the syntax issues I’m hitting!!

One Answer

This has the sweave tag, but what you show is not a complete LaTeX document with well delimited R code, but a chunk of hodgepodge of LaTeX plus R commands, including (maybe) the end of R code (@ line) but without any start of a R code chunk (<>>>= line), so it is difficult guess what are you doing really, but it seems unnecessarily complicated:

mwe

documentclass{article}
usepackage{graphicx}
begin{document}

<<objectnum,echo=F>>=
# Advanced method to set the variable:
graphicsrc <- 'example-image'
@

% Advanced method to use the variable as   filename of an image
<<echo=F,out.width="2cm",fig.cap="Example figure taking the variable name in R",fig.align='center'>>=
include_graphics(graphicsrc)
@

% Less advanced method 
begin{figure}[h]centering
includegraphics[width=2cm]{Sexpr{graphicsrc}}
caption{The same variable used in LaTeX code}
end{figure}

end{document}

BTW, as you can see in the example, you do not need to declare the extension of the image, except for disambiguation purposes (e.g., when you have foo.png and foo.pdf but you must use "foo.pdf" and not "foo.png").

On the other hand, do not see the use of [h] as a good practice. It was convenient only for this example.

Answered by Fran on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP