r - ggplot2 plot background colour gradient -
this code produces first plot below:
water.height <- seq(0, 5, 1) y <- seq(0, 1500, length.out = 6) df <- data.frame(water.height, y) library(ggplot2) ggplot(df, aes(water.height, y)) + geom_blank()+ theme_bw() 
i have photoshopped in blue background:

can produce same blue background r code?
the relevant link the ggplot2 approach given in comments. copied there:
library(grid) g <- rastergrob(blues9, width=unit(1,"npc"), height = unit(1,"npc"), interpolate = true) # grid.draw(g) library(ggplot2) ggplot(mtcars, aes(factor(cyl))) + # add gradient background annotation_custom(g, xmin=-inf, xmax=inf, ymin=-inf, ymax=inf) + geom_bar() # add data layer my own approach:
as usual, cannot compete simple elegance of baptiste's solutions problems grid graphics, here approach since went work:
gg.background.fill <- function(gg.plot, cols = "white", = "x") { #does not work facets stopifnot(which %in% c("x", "y")) which1 <- if (which == "x") "width" else "height" require(gridextra) g <- ggplotgrob(gg.plot) #g <- ggplotgrob(p) gg <- g$grobs findit <- vapply(gg, function(x) grepl("grid.gtree", x$name, fixed = true), true) n1 <- getgrob(gg[findit][[1]], "grill.gtree", grep=true)$name n2 <- getgrob(gg[findit][[1]], "panel.background.rect", grep=true)$name gg[findit][[1]]$children[[n1]]$children[[n2]]$gp$fill <- cols x <- gg[findit][[1]]$children[[n1]]$children[[n2]][[which]] w <- gg[findit][[1]]$children[[n1]]$children[[n2]][[which1]] attr <- attributes(x) x <- seq(0 + c(w)/length(cols)/2, 1 - c(w)/length(cols)/2, length.out = length(cols)) attributes(x) <- attr gg[findit][[1]]$children[[n1]]$children[[n2]][[which]] <- x w <- c(w)/length(cols) attributes(w) <- attr gg[findit][[1]]$children[[n1]]$children[[n2]][[which1]] <- w g$grobs <- gg class(g) = c("arrange", "ggplot", class(g)) g } p1 <- gg.background.fill(p, colorramppalette(c("red", "blue"))(100)) print(p1) 
p2 <- gg.background.fill(p, colorramppalette(c("red", "blue"))(100), "y") print(p2) 
this modifies existing background might considered advantage, in contrast annotation_custom approach doesn't work faceting. more work required that.
Comments
Post a Comment