I have a function that I use to build bar charts in R-markdown. I wonder if there is a better way to do the aes-part of my ggplot2 function. At the moment I use "eval(parse(text=" but that is kinda hard to read/understand.
I would like something that is more direct/readable. I tried aes_string but I think the "fill = factor()" part didn't work since while I did get a chart, I got an erroneous one (I got one big, fat bar). Were did I go wrong? Or is this the best way I can do my chart.
Reproducible example:
library("data.table")
library("ggplot2")
dt <- data.table(year.var = c(2014, 2014, 2014, 2015, 2015, 2015),
grp.var = c("Grp1", "Grp2", "Grp3", "Grp1", "Grp2", "Grp3"),
val.var = c(100, 200, 230, 105, 260, 23))
test <- function (dts,
x.var,
y.var,
fill.var,
order.var) {
setorderv(dts, order.var)
ggplot(dts,
aes(x = eval(parse(text = x.var)),
y = eval(parse(text = y.var)),
fill = eval(parse(text = fill.var))
)
) +
geom_bar(stat="identity", position="dodge")+
scale_fill_manual(values = c("#9badcd", "#5a6c9c"),
name = "Year")+
scale_y_continuous(labels = function(val.var) {
format(val.var, big.mark = " ",
scientific = FALSE)
}
)+
xlab("x.label") +
ylab("y.label")+
ggtitle("str.title")
}
test(dt, "grp.var", "val.var", "factor(year.var)", c("year.var"))