r - wrapping ggplot around a function -


i have following code seems work when have below

      p<-ggplot(data=x.all.er, aes(x=year, y=value, fill = (factor(x.all.er$strategy))))+        geom_bar(stat = 'identity',position = 'dodge', colour = "black") +       scale_fill_manual(values = mycols) +       scale_y_continuous(breaks=  seq(-0.3,0.3,by=0.025), labels = percent) +       ylab("eret") + theme(axis.title.y = element_text(size=15, face = "bold"))+       xlab("year") + theme(axis.title.x = element_text(size=15, face = "bold"))       print(p) 

but when try wrap around function gives me errors. appreciated. thanks!

      mybar<-function(ds, x, y, fillby, labels, mycols, xlabel, xbreaks,                                                              ylabel, title)           {      #my.cols =c("#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6",               # "#000000","#2171b5")        p<-ggplot(data=ds, aes(x=x, y=y, fill = fillby)+                geom_bar(stat = 'identity',position = 'dodge', colour = "black") +                scale_fill_manual(values = mycols) +               scale_y_continuous(breaks=  xbreaks, labels = percent) +               ylab(ylabel) +                theme(axis.title.y = element_text(size=15, face = "bold"))+                  xlab(xlabel) +                theme(axis.title.x = element_text(size=15, face = "bold"))               print(p)         } 

you can type x=x instead of x="x" in ggplot2 because ds data.frame attached within function (see ?with idea of what's going on). call ggplot looking variable named fillby in ds data frame, there isn't one. recommended in comments, way around aes_string function.

library(ggplot2) df = data.frame( xx=1:10, yy=1:10+rnorm(10) )  # regular use of ggplot ggplot(df,aes(x=xx,y=yy)) + geom_point()  # wrapping ggplot in function myggplot = function( df, x, y) {   ggplot(df,aes(x=x,y=y)) + geom_point() } myggplot(df,x,y) ## error in eval(expr, envir, enclos) : object 'x' not found 

the problem ggplot looking x column in data.frame because of ggplot(df,aes(x=x,y=y)) in myggplot. note work fine.

names(df) = c("x","y") myggplot(df,x,y) 

but this.

names(df) = c("x","y") myggplot(df,null,na) 

the fix:

df = data.frame( xx=1:10, yy=1:10+rnorm(10) ) myggplot2 = function( df, x, y) {   ggplot(df,aes_string(x=x,y=y)) + geom_point() } myggplot2(df,"xx","yy") 

if want avoid having write quotes, do

myggplot3 = function( df, x, y) {   ggplot(df,aes_string(x=deparse(substitute(x)),                        y=deparse(substitute(y)))) + geom_point()  } myggplot3(df,xx,yy) 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -