在渐变中绘制背景颜色 [英] 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()
我在这个蓝色背景中进行了 Photoshop 处理:
I have photoshopped in this blue background:
我可以用 R 代码生成相同的蓝色背景吗?
Can I produce the same blue background with R code?
推荐答案
ggplot2 方法 在评论中给出.从那里复制:
The relevant link to the ggplot2 approach was given in the comments. Copied from 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
<小时>
我自己的方法:
像往常一样,我无法与 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:
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
方法相比,它不适用于分面.为此需要做更多的工作.
This modifies the existing background which might be considered an advantage, but in contrast to the annotation_custom
approach it doesn't work with faceting. More work would be required for that.
这篇关于在渐变中绘制背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!