绘制渐变中的背景色 [英] Plot background colour in gradient
问题描述
此代码产生下面的第一个图:
This code produces the 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 this blue background:
我可以使用R代码产生相同的蓝色背景吗?
Can I produce the same blue background with R code?
推荐答案
与
我自己的方法: 和往常一样,我无法与 baptiste 的简单优雅解决方案竞争,以解决网格图形问题,但是在这里自从我从事所有工作以来,这就是我的方法: As usual, I cannot compete with the simple elegance of baptiste's solutions for problems with grid graphics, but here is my approach since I went to all that work: 这修改了可能被认为是优势的现有背景,但是与 This modifies the existing background which might be considered an advantage, but in contrast to the 这篇关于绘制渐变中的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
gg.background.fill <- function(gg.plot, cols = "white", which = "x") {
#does not work with 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)
annotation_custom
方法相反,它不适用于分面.为此,需要做更多的工作.annotation_custom
approach it doesn't work with faceting. More work would be required for that.