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?

3
  • 1
    Try aes_string instead of aes Commented Nov 4, 2014 at 6: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 Commented Nov 4, 2014 at 6: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. (stackoverflow.com/questions/20494238/… might help) Commented Nov 4, 2014 at 7:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.