0

I am trying to minimise my code by using functions for regularly repeated pieces of code. I have the need to create a significant number of charts so am wanting to simplify the readability.

Pretty well all of my data is in data.table structures which I am wanting to pass into my function to create a plot.

Reproducible example

library(ggplot2)
library(gtable)
library(grid)
grid.newpage()

dt.diamonds <- as.data.table(diamonds)

d1 <- dt.diamonds[,list(revenue = sum(price),
                        stones = length(price)),
                  by=clarity]

setkey(d1, clarity)

mybarchart <- function(data, xdata, ydata, xlabel="", ylabel="", myfill="", myscale="comma") {
ggplot(data, aes(x=xdata,y=ydata, fill=myfill)) +
geom_bar(stat="identity") +
labs(x=xlabel, y=ylabel) +
scale_y_continuous(labels=myscale, expand=c(0,0)) + 
scale_fill_identity(name="") + 
theme_bw()
}

mybarchart(d1, "clarity", "revenue")
#or
mybarchart(d1, "clarity", "revenue", "clarity", "revenue", "red", "dollar")

The error I get is Error in eval(expr, envir, enclos) : object 'xdata' not found and I suspect it is because I am using data.table rather than data.frame.

My approach to this kind of function has been take from examples like this and checking other posts on SO like this. As yet I haven't found anyone else demonstrating how to do this with a data.table rather than a data.frame

Any ideas how to make this work with a data.table?

Community
  • 1
  • 1
Dan
  • 2,625
  • 5
  • 27
  • 42
  • 1
    Try `aes_string` instead of `aes` – David Arenburg Nov 04 '14 at 06:22
  • `aes_string` has helped, however now I get an error in the actual call. Using `mybarchart(d1, "clarity", "revenue", xlabel="clarity", ylabel="revenue", myfill="red", myscale="dollar")` I get the error `Error in eval(expr, envir, enclos) : object 'red' not found` – Dan Nov 04 '14 at 06:32
  • 1
    you have added `myfill` inside `aes` - therefore `ggplot` is looking for a variable `"red"` to map the colour to. If you just want the bars red then the `fill` call should be outside `aes`. (http://stackoverflow.com/questions/20494238/implementing-geom-options-from-a-custom-function/22826702#22826702 might help) – user20650 Nov 04 '14 at 07:03

0 Answers0