Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting update_geom_defaults() in ggplot2

Tags:

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.

like image 925
Daniel Padfield Avatar asked Oct 28 '16 14:10

Daniel Padfield


1 Answers

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

old <- ggplot2:::check_subclass("line", "Geom")$default_aes # 2018
old <- ggplot2:::find_subclass("Geom","line")$default_aes # pre 2.0 I think

> 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
}
like image 164
Brandon Bertelsen Avatar answered Sep 28 '22 01:09

Brandon Bertelsen