简体   繁体   中英

changing aesthetic ggplot2 layer object inside function

i am trying to change an aesthetic of a geom that wasnt defined in the original plot call.

for example shape and 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

相同的p不同的形状和大小

clone a layer (l) from an existing plot object and have it not connect to the 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM