12

I've been using knitr with R base graphics and tikz output for a while now, and wanted to try out ggplot2 instead. However, this minimal example fails to produce any output with knitr 1.0.5:

\documentclass{article}
\begin{document}
<<dev = 'tikz'>>=
library(ggplot2)
d = data.frame(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9))
ggplot(d, aes(a, b, color = c)) + geom_point()
@
\end{document}

Instead, it fails with the message Error in UseMethod("depth"): no applicable method for 'depth' applied to an object of class "NULL". Executing the code in R or choosing the png device will result in the expected graph. Omitting the color aesthetics or factoring c work with tikzDevice as well, so the continuous color scale seems to be the problem.

Is there anything I am doing wrong, or is that a bug?

Metrics
  • 15,172
  • 7
  • 54
  • 83
Taral
  • 327
  • 1
  • 15
  • 3
    sounds like a bug of `tikzDevice`; given that it is not actively maintained now, I suggest you use other devices for this specific case. – Yihui Xie Feb 04 '13 at 23:18
  • what a pity, since I really like having my axis labels typeset by TeX. Maybe I'll have a look at tikzDevice when I get around to it. – Taral Feb 04 '13 at 23:46
  • @Yihui I just stumbled on the same bug. Any recommendations on what device to use? – RoyalTS Feb 17 '13 at 22:57
  • 1
    @RoyalTS you can use the default `pdf` device – Yihui Xie Feb 17 '13 at 23:11
  • @Yihui: Opened an issue with `tikzDevice` (with a MWE): https://github.com/yihui/tikzDevice/issues/132. – krlmlr Jan 20 '16 at 15:36

2 Answers2

6

I can get tikzDevice to work with your code by adding dev.off() to the end of the code block. For example:

cat("
    \\documentclass{article}
    \\begin{document}
    <<dev = 'tikz'>>=
    library(ggplot2)
    d = data.frame(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9))
    ggplot(d, aes(a, b, color = c)) + geom_point()
    dev.off()
    @
    \\end{document}
", "test_works.Rtex")
knit("test_works.Rtex")

works fine.

I have also noticed that if calling knit() through an active R session on the (original) code, I am left with an active tikz device ...

cat("
    \\documentclass{article}
    \\begin{document}
    <<dev = 'tikz'>>=
    library(ggplot2)
    d = data.frame(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9))
    ggplot(d, aes(a, b, color = c)) + geom_point()
    @
    \\end{document}
    ", file = "test_fails.Rtex")
knit("test_fails.Rtex")
dev.list()
Nate Pope
  • 1,696
  • 12
  • 11
  • thanks, you just saved me! how in the world did you figure that out? any idea why/what happens? – fabians Jul 29 '14 at 16:33
2

This was a bug, now resolved in the development version 0.10 of tikzDevice, which will hit CRAN soon. Until then, install using

devtools::install_github("yihui/tikzDevice")
krlmlr
  • 25,056
  • 14
  • 120
  • 217