在函数内部更改美观的ggplot2层对象 [英] changing aesthetic ggplot2 layer object inside function

查看:77
本文介绍了在函数内部更改美观的ggplot2层对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试改变原图调用中未定义的几何图形的美感.

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

例如形状和大小

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

推荐答案

从现有绘图对象克隆图层(l),使其不连接到原始绘图

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)
}

这篇关于在函数内部更改美观的ggplot2层对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆