Pierre-louis Stenger
Pierre-louis Stenger

Reputation: 301

How to make a gradient colour in strip.background in ggplot?

I try to create a colour gradient in a fill arguments in the strip.background() function of ggplot2() package.

Here a picture of what I would like to have: gradient

And the code I use to try to have it:

# Charge random data
data('mtcars')

# Create fake variable in order to create title into coloured box
mtcars$tempvar <- "My title"

# Run the ggboxplot
ggboxplot(mtcars, x = "cyl", y = "qsec", 
          color = "cyl", 
          palette = c("#E7B800", "#FC4E07",  "#00AFBB"),
          ylab = "cyl", xlab = "qsec",
          legend = "none") + 

 facet_grid(. ~ tempvar) +
  theme(strip.background = element_rect(fill="darkgreen"),
        strip.text = element_text(size=15, colour="white") )

This gives:

green

So I try to create a palette from the scale_color_manual() or from colorRampPalette(c("yellow", "green")) and put in the element_rect() but this didn't work.

I also try to upload a picture of gradient coloured background from google image, and paste it on the right place with annotation_custom(rasterGrob(image))like in this blog but this does not work either.

Any advice for programming this in a proper way will be very appreciated.

Upvotes: 1

Views: 2777

Answers (1)

Z.Lin
Z.Lin

Reputation: 29095

Technically? This can be done. (Whether it's chartjunk or good practice is another matter...)

p <- ggplot(mtcars, aes(mpg, drat)) + 
  geom_point() + 
  facet_grid(~"facet title") 

# basic demonstration
p +
  theme(strip.background = 
          element_gradient(fill1 = "black", fill2 = "white"))

# with different gradient direction & outline specifications
p +
  theme_minimal() +
  theme(strip.background = 
          element_gradient(fill1 = "brown", fill2 = "salmon",
                           direction = "vertical",
                           color = "white", size = 2,
                           linetype = "dotted"))

# with horizontal / vertical facets in different gradient directions
p + facet_grid("vertical title" ~ "horizontal facet title") +
  theme_classic() +
  theme(strip.background = element_gradient(fill1 = "green", fill2 = "yellow", size = 1),
        strip.background.y = element_gradient(direction = "vertical"))

demonstrations

1. Defining element_gradient as an alternative to element_rect:

element_gradient <- function(fill1 = NULL, fill2 = NULL, direction = NULL,
                             colour = NULL, size = NULL,
                             linetype = NULL, color = NULL, inherit.blank = FALSE) {
  if (!is.null(color))  colour <- color
  structure(
    list(fill1 = fill1, fill2 = fill2, direction = direction,
         colour = colour, size = size, linetype = linetype,
         inherit.blank = inherit.blank),
    class = c("element_gradient", "element")
  )
}

element_grob.element_gradient <- function(
  element, 
  fill1 = "white", fill2 = "red", direction = "horizontal", # default: white-red gradient
  x = 0.5, y = 0.5, width = 1, height = 1, colour = NULL, 
  size = NULL, linetype = NULL, ...) {

  # define gradient colours & direction
  if(!is.null(element$fill1)) fill1 <- element$fill1
  if(!is.null(element$fill2)) fill2 <- element$fill2
  if(!is.null(element$direction)) direction <- element$direction  
  image <- colorRampPalette(c(fill1, fill2))(2)  
  if(direction == "horizontal") {
    image <- matrix(image, nrow = 1)
  } else {
    image <- matrix(image, ncol = 1)
  }

  gp <- grid::gpar(lwd = ggplot2:::len0_null(size * .pt), col = colour, lty = linetype)
  element_gp <- grid::gpar(lwd = ggplot2:::len0_null(element$size * .pt), col = element$colour,
                     lty = element$linetype, fill = NA)  
  grid::grobTree(
    grid::rasterGrob(image, x, y, width, height, ...),
    grid::rectGrob(x, y, width, height, gp = utils::modifyList(element_gp, gp), ...))
}

2. Force ggplot to accept element_gradient instead of element_rect for strip.background / strip.background.x / strip.background.y:

# make a copy of ggplot's global variables / settings, & modify its element_tree
ggplot_global.new <- ggplot2:::ggplot_global
ggplot_global.new$element_tree$gradient <- ggplot2:::el_def("element_gradient")
ggplot_global.new$element_tree$strip.background <- ggplot2:::el_def("element_gradient", "gradient")
ggplot_global.new$element_tree$strip.background.x <- ggplot2:::el_def("element_gradient", "strip.background")
ggplot_global.new$element_tree$strip.background.y <- ggplot2:::el_def("element_gradient", "strip.background")

3. Force ggplot not to complain about it, by manually overriding its checks:

Note: While I don't usually like modifying a package's internal functions (even if it's on a temporary basis), in this case the alternative would involve defining a series of intermediate functions based off existing un-exported functions in the ggplot2 package, & modifying each in turn. Given the number of steps/functions involved, I think that approach would be even more fragile.

  1. Run trace(ggplot2:::merge_element.element, edit = TRUE) and replace
if (!inherits(new, class(old)[1])) {
  stop("Only elements of the same class can be merged", call. = FALSE)
}
    

with

if (!inherits(new, class(old)[1]) & class(new)[1] != "element_gradient") {
  stop("Only elements of the same class can be merged", call. = FALSE)
}
  1. Run trace(ggplot2:::validate_element, edit = TRUE) and replace
else if (!inherits(el, eldef$class) && 
         !inherits(el, "element_blank")) {
  stop("Element ", elname, " must be a ", eldef$class, " object.")
}

with

else if (!inherits(el, eldef$class) && 
         !inherits(el, "element_blank") && 
         eldef$class != "element_gradient") {
  stop("Element ", elname, " must be a ", eldef$class, " object.")

4. When done, run the following to end the insanity & revert to normal ggplot behaviour:

ggplot_global.new$element_tree$strip.background <- ggplot2:::el_def("element_rect", "rect")
ggplot_global.new$element_tree$strip.background.x <- ggplot2:::el_def("element_rect", "strip.background")
ggplot_global.new$element_tree$strip.background.y <- ggplot2:::el_def("element_rect", "strip.background")

untrace(ggplot2:::merge_element.element)
untrace(ggplot2:::validate_element)

Upvotes: 8

Related Questions