r - changing aesthetic ggplot2 layer object inside function -
i trying change aesthetic of geom wasnt defined in original plot call.
for example shape , size
p=iris%>%ggplot(aes(x=sepal.length,y=sepal.width,colour=species))+geom_point()+theme_bw() change_shape=function(a){ a$layers[[1]]$aes_params[['shape']]=5 a$layers[[1]]$aes_params[['size']]=10 return(a) } pnew=change_shape(p) p
clone layer (l) existing plot object , have not connect original plot
clonelayer=function(l){ layer.names=c('mapping','data','geom','position', 'stat','show.legend','inherit.aes', 'aes_params','geom_params','stat_params') x=sapply(layer.names,function(y){ b=l[[y]] if('waiver'%in%class(b)) b=null if(y=='geom') b=eval(parse(text=class(b)[1])) if(y%in%c('position','stat')) { b=gsub(y, "", tolower(class(b)[1])) } b }) x$params=append(x$stat_params,x$geom_params) x$params=append(x$params,x$aes_params) x$params=x$params[!duplicated(names(x$params))] x$geom_params<-x$aes_params<-x$stat_params<-null do.call(layer,x) }
Comments
Post a Comment