R using tikzDevice in a LaTeX document with knitr

I have a problem with ggplot2, tikzDevice and knitr working together. I am working with RStudio and am trying to incorporate some R-graphics into a Latex document. I used a very simple example:

\documentclass{article} \begin{document} \begin{figure} <<fig1,eval=TRUE,echo=FALSE,dev='tikz'>>= library(ggplot2) library(tikzDevice) qplot(displ, hwy, data = mpg, colour = factor(cyl)) @ \end{figure} \end{document} 

But the pdf file is not output, and the following error message appears:

 Error in getMetricsFromLatex(TeXMetrics) : TeX was unable to calculate metrics for the following string or character: hwy Common reasons for failure include: * The string contains a character which is special to LaTeX unless escaped properly, such as % or $. * The string makes use of LaTeX commands provided by a package and the tikzDevice was not told to load the package. The contents of the LaTeX log of the aborted run have been printed above, it may contain additional details as to why the metric calculation failed. Calls: knit ... widthDetails.text -> grid.Call -> <Anonymous> -> getMetricsFromLatex Execution halted 

This issue has been addressed here , but the proposed solution does not work for me. Any idea?

+7
r knitr ggplot2 latex tikz
source share
2 answers

Perhaps a collision with another package that you did not include in your simple example? For me, I received an error message due to some collision between the xcolor package and tikz . I called xcolor before tikz , no problem, but as soon as I set dev="tikz" to the chunk option, I got the same error as you. As soon as I removed \usepackage{xcolor} , everything worked.

+1
source share

I added in the R code

 options(tikzMetricPackages = c("\\usepackage[utf8{inputenc}", "\\usepackage[T1]{fontenc}", "\\usetikzlibrary{calc}", "\\usepackage{amssymb}")) 

a source

+1
source share

All Articles