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?
aes_stringinstead ofaesaes_stringhas helped, however now I get an error in the actual call. Usingmybarchart(d1, "clarity", "revenue", xlabel="clarity", ylabel="revenue", myfill="red", myscale="dollar")I get the errorError in eval(expr, envir, enclos) : object 'red' not foundmyfillinsideaes- thereforeggplotis looking for a variable"red"to map the colour to. If you just want the bars red then thefillcall should be outsideaes. (stackoverflow.com/questions/20494238/… might help)