[datatable-help] ggplot2 and data.table

Timothée Carayol timothee.carayol at gmail.com
Sun Aug 14 22:55:58 CEST 2011


Ah sorry -- the definition of ggplotDT() should be, of course:

ggplotDT <- function(...) {
 ggplot(, aesDT(...))
}

(aes_now() was an artifact from Hadley Wickham's Stack Overflow tip)

t


2011/8/14 Timothée Carayol <timothee.carayol at gmail.com>

> Hi,
>
> For some time I have been wishing that data.table and ggplot2 could play a
> bit nicer together.
> For example, I would like this to work but it doesn't:
>
> > test <- data.table(a=1:10, b=1:10)
> > test[, ggplot() + geom_line(aes(x=a, y=b))]
> Error in eval(expr, envir, enclos) : object 'a' not found
>
> I spent a few dozen minutes trying to understand what was going on (and
> stumbling upon this useful advice from Hadley Wickham<http://stackoverflow.com/questions/3737619/how-can-i-pass-a-ggplot2-aesthetic-from-a-variable>),
> and it turns out that it's very easy to fix (though the fix is not very
> pretty).
> Datatable-help, I present you with.. aesDT and ggplotDT.
>
>
> aesDT <- function(...) {
>  aes <- structure(list(...),  class = "uneval")
>  rename_aes(aes)
> }
>
> Using aesDT() instead of aes() whenever you are in a data.table (or in a
> with()) will now work. That is pretty much all you need, but I thought I'd
> go just one tiny step further with ggplotDT():
>
> ggplotDT <- function(...) {
>  ggplot(, aes_now(...))
> }
>
> which makes the following possible:
>
> test[, ggplotDT(x=a, y=b) + geom_line()]
>
> i.e. put the aesthetics directly as arguments, saving a few keystrokes and
> a pair of brackets.
> Tiny problem that I have yet to solve: you now have to explicitly give the
> name of all the aesthetics; aes() is sufficiently clever to guess them if
> they're in the right order, but the logic does not seem to carry over
> straightforwardly to aesDT().
>
> I know I'll be using these, so I thought maybe other people here might be
> interested.
>
> Timothee
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20110814/c09b54f2/attachment.htm>


More information about the datatable-help mailing list