39

Problem description

I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor fix. The offending lines are

mpl.rcParams.update({"text.usetex": True})
...
plt.title(r'Some Latex with symbol \$')

It is LaTeX trying to interpret the \$ which is throwing issues. As far as I can tell this should be correctly escaped. If I remove the \$ everything works as expected, (or if I replace it with e.g. $e=mc^2$).

The error message

Quitting from lines 31-34 (example.Rmd) 
Error in py_call_impl(callable, dots$args, dots$keywords) : 
  RuntimeError: Evaluation error: KeyError: b'tcrm1200'

Detailed traceback: 
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\pyplot.py", line 722, in savefig
    res = fig.savefig(*args, **kwargs)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
    self.canvas.print_figure(fname, **kwargs)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
    super().print_figure(*args, **kwargs)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
    **kwargs)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
    self.figure.draw(renderer)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py"
Calls: <Anonymous> ... py_capture_output -> force -> <Anonymous> -> py_call_impl
Execution halted

MWE

The following is a .Rmd file running on Rstudio 1.2.5001 (should be using Python 3.7 with Conda3, but I'm not so sure how to dig out the specifics on Windows...).

---
output: pdf_document
---


```{r}
library(reticulate)
```

```{python, echo=FALSE, include=FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\Users\Harry\Anaconda3\Library\plugins\platforms'
```

```{python, echo=FALSE, include=FALSE}
import matplotlib as mpl
import matplotlib.pyplot as plt
# Setting some default plotting features to give nicer plots. This can be commented out for beginners. 
rc_fonts = {
    "text.usetex": True,
    'text.latex.preview': True, # Gives correct legend alignment.
    'mathtext.default': 'regular',
    'figure.figsize': (6, 4),
    "font.family": "serif",
    "font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
```

```{python}
plt.plot([0, 2, 1, 4])
plt.title(r'Some Latex with symbol \$')
plt.show()
```
Bastian Venthur
  • 12,515
  • 5
  • 44
  • 78
oliversm
  • 1,771
  • 4
  • 22
  • 44
  • 6
    I know nothing about mathplotlib, but maybe you could try `\textdollar`? – samcarter_is_at_topanswers.xyz Oct 24 '19 at 12:03
  • It's a possible work around, but doesn't explain what's going wrong... – oliversm Oct 28 '19 at 22:59
  • 5
    Try to escape with two backslashes: `\\$`. – user7669 Oct 29 '19 at 12:03
  • @user7669 I had tried this but this just threw different errors, which if I recall were to do with a missing `$` for a math mode. (I can't readily perform this check as I don't have the windows machine to hand). Plus in python the `r'...'` prefix means the string is taken at its raw face-value, so the `\` isn't treated as its usual python escape character (but should be later interpreted as a LaTeX escape character). – oliversm Oct 30 '19 at 00:39
  • @Gowachin it was a problem I was having with all my students running windows. – oliversm Apr 02 '21 at 20:03
  • Have you tried running in Python without the R wrapper? I put the Python code into a `.py` file and it works for me when I run it on Windows in Anaconda. It does take a while to compile the text via LaTeX though. – ramzeek Oct 27 '21 at 03:18
  • @wikikikitiki this was for a course of using python with R markdown, so the r wrappers are required. – oliversm Oct 27 '21 at 05:22
  • @oliversm sure, but if it works in raw python/matplotlib on your system, that is valuable troubleshooting info – Paul H Mar 28 '22 at 14:53
  • I can confirm your code works in "pure" Python, and I'm inclined to think that something is messed up when R passes the code to Python, but my only suggestion is to try different number of backslashes, two, three, why not four... my bet is on three backslashes, one to escape the second one and the third to escape the "$". – gboffi Dec 27 '22 at 22:19

3 Answers3

1

Running your code on the most recent version of RStudio (2022.12.0), on Windows 11, with the current default python version install from miniconda (3.10.8) produces no errors:

enter image description here

iacob
  • 20,084
  • 6
  • 92
  • 119
-3

Just remove the backslash! The string is already protected in single quote format.

plt.title(r'Some Latex with symbol $')
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32632872) – Deenadhayalan Manoharan Sep 08 '22 at 09:32
  • @DeenadhayalanManoharan This answer is a legitimate answer to the question. Then it is wrong, but that's a different issue, that on SO is remedied by down voting. – gboffi Dec 27 '22 at 22:24
-4

I think u should type in text in 'markdown' section of JupyterNotebook in Ananconda, type the python code in the 'codes' section of the notebook too and finally save it as PDF via LaTeX in the JupyterNotebook. This will solve your problems individually and give u the output I think u r looking for.