本文介绍了绘制渐变中的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码产生下面的第一个图:
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?
推荐答案
与 ggplot2方法.从那里复制:
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.
这篇关于绘制渐变中的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!