gg_themelock | R Documentation |
ggThemeLock introduces the ability to “lock” the state of a ggplot theme during a ggplot's assembly. When gg_themelock()
is used in the composition of a ggplot (e.g., using the the '+
' operator), the theme elements are stored and the object is placed in a “locked” state. The subsequent addition of theme elements that have been previously locked is ignored, and the saved theme elements are preserved. New theme elements that haven’t been locked can still be added.
gg_themelock(object) is.themelocked(object)
object |
A ggplot or theme object to apply a lock to; optional. See description and examples. |
A plot object can be locked by either including gg_themelock()
in its assembly using the '+
' operator, or by passing the plot object as an argument to gg_themelock()
. A theme object can only be locked by passing it as the argument to gg_themelock()
. See examples below.
Take note, addition of ggplot objects is not necessarily associative or commutative. With this in mind, ggThemeLock was built to be as intuitive as possible. Calls to gg_themelock()
will "lock" the state of the theme on the left-hand (LHS) side of an addition expression. However, if the right-hand (RHS) side of an addition expression is in a "locked" state (e.g., adding a locked theme to a theme), the addition behavior depends on whether the LHS side is also locked. If both the LHS and RHS are locked, the locked elements are merged and re-locked (with priority going to the LHS); if the LHS is unlocked and the RHS is locked, the locked elements of the RHS remain locked.
library(ggplot2) # ======================================== # set a theme element and lock the state ggplot(mtcars) + aes(x = mpg, y = hp) + geom_point() + theme(axis.text = element_text(color = "red")) + gg_themelock() + theme( axis.text = element_text(color = "blue"), # this element is locked and not applied axis.title = element_text(color = "green") # this element is applied ) # ======================================== # build a theme and lock it, then use it in a plot my_theme <- theme( axis.text = element_text(color = "blue"), axis.title = element_blank() ) my_theme <- gg_themelock(my_theme) ggplot(mtcars) + aes(x = mpg, y = hp) + geom_point() + my_theme + theme_classic() # elements in this theme that have been defined by my_theme are ignored # ======================================== # lock and relock a theme multiple times during construction # (try commenting out the gg_themelock() lines one at a time) ggplot(mtcars) + aes(x = mpg, y = hp) + geom_point() + theme(axis.text = element_text(color = "blue")) + gg_themelock() + theme( axis.text = element_text(color = "red"), axis.title = element_blank() ) + gg_themelock() + theme_bw()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.