0

Im using the latex2exp package to make some plots in R with latex expressions in the labels. TeX("$\lambda$") on the xlabel doesn't print what it needs to. The documentation said to use TeX(r'($\lambda$)') which doesnt work, and TeX("$\\lambda$") doesnt work either. For example, plot(1:5, 1:5, xlab = Tex(r'($\lambda$)')) will not have the lambda character on the xlabel. How should I fix this?

luki
  • 1,796
Robert
  • 11

2 Answers2

1

With knitr and the tikz device there are no need of latex2exp and the TeX() function, only escape the backslash.

mwe

\documentclass{article}
\begin{document}
<<foo,echo=F,dev='tikz',fig.width=3, fig.height=3, fig.align='center'>>=
plot(1:5, 1:5, xlab = '$\\lambda$ with \\LaTeX')
@
\end{document}

Fran
  • 80,769
  • I just installed those packages and tried it. It prints: $\lambda$

    on the xlabel

    – Robert Apr 04 '21 at 01:53
  • @RobertFerydouni Have you tested just the above R Sweave file (save it with .Rnw extension) "as is" or only the R chunk? I have included the expected output in the PDF. – Fran Apr 04 '21 at 09:06
  • Yes. It seems I have the same problem as my original comment. I do not have a latex compiler on my machine, could this be the problem? I try to import that library and it says "No Latex compiler could be found". So maybe it isnt noticing the $ symbols because of that – Robert Apr 04 '21 at 17:47
  • Of course, you need a latex compiler. Using R one way is installing tinytex – Fran Apr 05 '21 at 02:01
  • I just installed tinytex, and I tried running the the R chunk only, as well as running the the file as is, and it still prints the characters '$\lambda$ with \LaTeX' on the xlabel. What else could this be attributed to – Robert Apr 05 '21 at 02:58
  • And have you installed the tikzDevice? – Fran Apr 05 '21 at 03:05
  • Yes I have. And knitr – Robert Apr 05 '21 at 03:30
  • Sure that you have run install.packages('tinytex') and then also tinytex::install_tinytex()? – Fran Apr 05 '21 at 03:52
  • Yes, I installed both. I also tried running that code on the console also, and I get a Error: unexpected input in "" ,after the \documentclass{article} command. Similar erros show up with the "<<" and "@", so maybe the LaTeX commands aremt being recognized as LaTeX – Robert Apr 05 '21 at 04:06
  • You cannot do that, nor run only the R chunk. The .Rnw file must be converted to true .tex file and the compiled as any latex file. The way to do this is load the .Rnw file with Rstudio and click on the "compile PDF" icon or see here to use the command line. – Fran Apr 05 '21 at 04:22
  • I tried to click the Compile PDF button and got: LaTeX Error: File 'ae.sty' not found. Then below that it says: Fatal error occurred, no output PDF file produced. Also, this may or may not be important, but when I run the file or when I do what I jut did, this command automatically puts itself in the file: \SweaveOpts{concordance=TRUE} – Robert Apr 05 '21 at 04:30
  • (1)\SweaveOpts should not appear. You are trying to compile the file with Sweave, not with knitr. Check you RStudio configuration! (2) "*.sty not found": tinytex only install a basic set of latex packages, but missing packages should be downloaded automatically when needed. If after some compilations still some file is not found, use tlmgr to install the missing latex packages. – Fran Apr 05 '21 at 05:03
  • Ah! I finally got your code to work. Thank you so much. How should I go about editing the above code, or writing a rnw file myself so I can generate my own plots? I tried copy and pasting some r code I had in between the << and the @ but that doesnt work. My code has a for loop generating multiple plots for different parameter values – Robert Apr 05 '21 at 05:20
  • I just tried clicking Compile PDF again but for my code with this method, but the pdf doesnt show any of the plots. I instead had a pathism command, which I checked all the plots were there, but I have the same problem of it printinig "$Latex expression$" – Robert Apr 05 '21 at 05:30
  • You are doing something wrong. Try first with some of the many working examples of R plots using .Rnw files in this site, for example here and here – Fran Apr 05 '21 at 05:40
0

The documentation of latex2exp mentions the following:

Before R 4.0, it is necessary to escape the backslash within the string literal: therefore, one writes '$\\gamma$' rather than '$\gamma$' (the latter will cause an error).

After R 4.0, it is recommended to use the new raw string literal syntax (see ?Quotes). The syntax looks like r"(...)", where ... can contain any character sequence, including \:

You can find your R version when you start R, the version number is printed in the terminal window. Note that the R command is TeX() (so upper case T, lower case e, upper case X, which is the standard capitalization of TeX, and not Tex as written in the final snippet in the question - but I guess that is a typo.

The following works in R 3.6:

library(latex2exp)
plot(1:5, 1:5, xlab = TeX("$\\lambda$"))

Result:

enter image description here

For R 4.0 and above you can use the new syntax. Note that you have to explicitly include the delimiter within the string. In the example above the delimiters are '( and )'. The following works when tested in R 4.0.3:

library(latex2exp)
plot(1:5, 1:5, xlab = TeX(r'($\lambda$)'))

This does not work if you have the closing sequence )' somewhere inside of your string. In that case you can extend the delimiter with dashes, for example:

plot(1:5, 1:5, xlab = TeX(r'---($\lambda\cdot(a+b)'$)---'))
# more readable:
plot(1:5, 1:5, xlab = TeX(
   r'---(
   $\lambda\cdot(a+b)'$
   )---'
))
Marijn
  • 37,699
  • I ave R version 4.0.4. I ran it with what you posted for R 4 and above, and I get a Error: malformed raw string literal – Robert Apr 03 '21 at 21:20
  • @RobertFerydouni strange. I'll try later if I can access a newer version of R to try out the syntax. – Marijn Apr 03 '21 at 21:38
  • @RobertFerydouni I didn't put the correct delimiters in my 4.0+ example, now corrected. – Marijn Apr 05 '21 at 13:28
  • This doesnt seem to work. It prints: paste("", "", lambda, , , , "") on the xlabel – Robert Apr 05 '21 at 22:02
  • @RobertFerydouni Maybe some of your packages need to be updated? I tried on https://rdrr.io/snippets/ with the code library(latex2exp) print(R.version) plot(1:5, 1:5, xlab = TeX(r'($\lambda$)')) which gives the expected plot (that website uses R 4.0.3). Or maybe there is an issue in how you store and run the code - do you type it directly in Rstudio, or do you run it from the command line/terminal, or through a file? Maybe there are some issues with interpreting/escaping special characters there, especially if it goes through the terminal. – Marijn Apr 06 '21 at 07:47
  • I have been typing it directly into rstudio – Robert Apr 06 '21 at 16:30
  • I mentioned in the other answer that I have a pathism command directing the generated plots to a folder on my machine, and Im thinking it might be a problem with how the created pdfs are being stored – Robert Apr 06 '21 at 16:41
  • @Robert And does it work if you generate the plots in the RStudio plotting window, instead of saving it to a pdf? – Marijn Apr 06 '21 at 16:50
  • No. Nothing even shows up in that window when I run the code that way. Im not sure if it can even do that, because I have a for loop generating multiple plots. – Robert Apr 06 '21 at 17:45
  • @Robert and what if you try just the code from your question, with the single plot of 1:5? And does a single plot without LaTeX labels work? – Marijn Apr 06 '21 at 18:38
  • The single plot does work both with and without latex expression, which leads me to think something is not working right with how my code is being processed. – Robert Apr 06 '21 at 20:16