重置ggplot2中的update_geom_defaults() [英] Resetting update_geom_defaults() in ggplot2

查看:216
本文介绍了重置ggplot2中的update_geom_defaults()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果您使用 ggplot2 :: update_geom_defaults()例如:

  ggplot2 :: update_geom_defaults(line,list(color ='red',linetype = 2 ))

你如何将ggplot2恢复到原来的默认值?



到目前为止,我发现的是检查是否加载了 ggplot2 ,如果它是分离并重新加载的因此,重置默认值,但这似乎是一个可怕的黑客。

  if(ggplot2%in%(.packages ()){
suppressMessages(suppressWarnings(detach(package:ggplot2,unload = TRUE)))
suppressMessages(suppressWarnings(library(ggplot2)))}


必须有一个简单的方法。

解决方案



 老<  -  ggplot2 ::: find_subclass( Geom,line)$ default_aes 

>旧
* color - > 黑色
*大小 - > 0.5
*线型 - > 1
* alpha - > NA

update_geom_defaults(line,list(color =red))

> ggplot2 ::: find_subclass(Geom,line)$ default_aes
$ color
[1]red

$ color
[1]黑色

$ size
[1] 0.5

$线型
[1] 1

$ alpha
[1] NA

然后返回:

  update_geom_defaults(line,old)

在我看来,这是笨重的。创建一个绘图函数,或者简单地添加或删除 + geom_line()会更好。设置geom_defaults的想法是为整个会话设置默认值。



示例函数:

  my_plotfun < - 函数(x,opt0,opt1,opt2,opt3){
p < - ggplot(x,aes(...))
if(opt0)如果(opt1)
p < - p + coord_flip()
if(opt2)
...
p < - p + geom_line(...)

p
}


This sounds so simple and I am sure it is...

If you use ggplot2::update_geom_defaults() such as:

ggplot2::update_geom_defaults("line", list(colour = 'red', linetype = 2))

How do you return ggplot2 to its original defaults?

So far all I have found is to check if ggplot2 is loaded and if it is then detach and reload it therefore "resetting" the defaults, but that seems like a terrible hack.

  if("ggplot2" %in% (.packages())){
     suppressMessages(suppressWarnings(detach("package:ggplot2", unload=TRUE)))
     suppressMessages(suppressWarnings(library(ggplot2)))}

There must be an easier way.

解决方案

You can "save" the defaults and then reapply them:

old <- ggplot2:::find_subclass("Geom","line")$default_aes

> old 
* colour   -> "black"
* size     -> 0.5
* linetype -> 1
* alpha    -> NA

update_geom_defaults("line", list(color = "red"))

> ggplot2:::find_subclass("Geom","line")$default_aes
$color
[1] "red"

$colour
[1] "black"

$size
[1] 0.5

$linetype
[1] 1

$alpha
[1] NA

And then back:

update_geom_defaults("line", old)

This is clunky, in my opinion. You're much better off creating a plot function, or simply adding or removing + geom_line(). The idea behind setting geom_defaults is to have defaults for the entire session.

Example plot function:

my_plotfun <- function(x, opt0, opt1, opt2, opt3) {
 p <- ggplot(x, aes(...))
 if(opt0) 
   p <- p + geom_line(...)
 if(opt1) 
   p <- p + coord_flip()
 if(opt2)
   ...
 p
}

这篇关于重置ggplot2中的update_geom_defaults()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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