r - Is there a way to use function argument as a label in ggplot2? -


quick question: if want run function, such plt.diff(dataset1), , in output graph, want function use name "dataset1" y-axis label, how can done?

plt.diff <- function(x){    x$kind <- as.factor(x$kind)     ggplot(x,aes(x=as.factor(nodes), fill= age)) + labs(title = 'difference plot',                 x = 'points', y = deparse(substitute(x)) ) + geom_text(                 aes(label = nodes, y = diff)) +                 geom_bar(stat="identity", aes(y = diff)) +                  geom_bar(stat="identity", aes( y = (diff*(-1)))) +                  coord_flip()} 

as can see, i've tried deparse(substitute(x)) , doesn't work. output y-axis currently: structure(list(nodes= structure(c(1l, 2l, 3l, 4l, 5l, 6l, 7l))))

i extract name of object passed function on via deparse(substitute(x)), , pass ggplot. ensures name of object based on function argument passed plt.diff , not ggplot within plt.diff.

using toy data set:

dataset1 <- data.frame(nodes = 1:10, kind = 1:10, age = rpois(10, 20), diff = rpois(10,5))  library(ggplot2)  plt.diff <- function(x){   x_name <- deparse(substitute(x))     x$kind <- as.factor(x$kind)   ggplot(x, aes(x = as.factor(nodes), fill = age)) +      labs(title = 'difference plot', x = 'points', y = x_name) +      geom_text(aes(label = nodes, y = diff)) +     geom_bar(stat="identity", aes(y = diff)) +      geom_bar(stat="identity", aes( y = (diff*(-1)))) +      coord_flip()}  plt.diff(dataset1) 

ggplot2 bar chart


Comments