Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ggplot2's continuous color scale incompatible with knitr's tikzDevice?

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?

like image 809
Taral Avatar asked Feb 04 '13 14:02

Taral


2 Answers

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()
like image 114
Nate Pope Avatar answered Sep 24 '22 03:09

Nate Pope


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")
like image 39
krlmlr Avatar answered Sep 24 '22 03:09

krlmlr