Daniel Padfield Daniel Padfield - 1 year ago 82
R Question

Resetting update_geom_defaults() in ggplot2

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

If you use

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

There must be an easier way.

Answer Source

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
[1] "red"

[1] "black"

[1] 0.5

[1] 1

[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(...))
   p <- p + geom_line(...)
   p <- p + coord_flip()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download