2015-05-09 128 views
4

此代码生成低于第一情节:GGPLOT2绘图背景颜色梯度

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() 

enter image description here

我已经在这个蓝色背景Photoshop处理:

enter image description here

我可以产生相同的与R代码的蓝色背景?

+1

因此,使用此渐变为数据点着色是不够的? –

+0

没有,因为不得不在Photoshop中做的事情杀死的重复性 – luciano

+1

此链接可能:http://r.789695.n4.nabble.com/plot-background-excel-gradient-style-background-tp4632138p4634954.html – scoa

回答

8

在评论中给出了the ggplot2 approach的相关链接。从那里复制:

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的解决方案与网格图形问题古朴典雅竞争,但这里是我的方法因为我去了所有的工作:

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) 

resulting plot

p2 <- gg.background.fill(p, colorRampPalette(c("red", "blue"))(100), "y") 
print(p2) 

enter image description here

这会修改现有的背景,可以看作是一个优势,但相较于annotation_custom方法它不与小面的工作。为此需要做更多的工作。

+3

有没有方法跨越对角线做到这一点?这样红色是左下角,蓝色是右上角? – Jibril