I need to graph data using different consolidation, and would like to do it inside ggplot.
x <- c(1,2,1,2,1,2,1,2,1)
cust <- c("a", "b", "c", "a", "b", "c", "a", "b", "c")
prod <- c("p1", "p1", "p2", "p2", "p1", "p1", "p2", "p2", "p1")
qty <- c(11,12,13,14,15,16,17,18,19)
dt <- data.table(x, cust, prod, qty)
rm(cust, prod, qty, x)
So, if I choose to consolidate by cust
I get:
print.dt <- function(dt, x, qty, anchor_var_, geom) {
ggplot(dt, aes(x=x, y = qty, color = get(anchor_var_))) +
stat_summary(fun.y=sum, geom=geom, size=1.5 , aes(group=get(anchor_var_)))
}
anchor <- "cust"
print.dt(dt,x,qty,anchor, geom = "line")
Otherwise, If I choose to consolidate by prod
, then:
anchor <- "prod"
print.dt(dt,x,qty,anchor, geom = "line")
However, this code calls get()
twice. Is there another way to convert only once and apply for two instances? I tried:
print2.dt <- function(dt, x, qty, anchor_var_, geom) {
anchor_var <- get(anchor_var_)
ggplot(dt, aes(x=x, y = qty, color = anchor_var)) +
stat_summary(fun.y=sum, geom=geom, size=1.5 , aes(group=anchor_var))
}
anchor <- "prod"
print2.dt(dt,x,qty,anchor, geom = "line")
But it doesn´t work.