R:ggplot背景渐变着色

时间:2016-09-22 07:09:07

标签: r ggplot2 gridextra r-grid grob

我想用渐变着色生成ggplot,填充绘图面板及其背景,如下所示。

enter image description here

如您所见,渐变背景着色包含绘图面板及其背景。目前,我只知道所需解决方案的“近似”:

library(ggplot2)
library(grid)
library(gridExtra)
reds <- c("#7B0664", "#E32219")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1, "npc"),   
                interpolate = TRUE) 
ggplot(data = economics, aes(x = date, y = unemploy)) + 
     annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + 
     geom_line( alpha=1, color = "white", size = 0.5 ) +
     xlab("Years") + ylab("Unemployed [thousands]") +
     theme(plot.background = element_rect(fill=reds[2]))

使用上面显示的代码,绘图面板会在轴边界内呈现渐变色,但不会使用此类渐变着色跨越整个背景。主题(plot.background = ...)能够填充剩余的背景,但它似乎无法利用渐变着色。进一步说明应该对整个绘图背景应用相同的渐变着色。

任何建议将不胜感激。感谢。

1 个答案:

答案 0 :(得分:3)

您可以在rasterGrob上打印/绘制绘图,

enter image description here

library(ggplot2)
library(grid)
library(ggthemes)

reds <- c("#7B0664", "#E32219")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1, "npc"), interpolate = TRUE)
p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
  geom_line( alpha=1, color = "white", size = 0.5 ) +
  xlab("Years") + ylab("Unemployed [thousands]") +
  theme_base() + 
  theme(panel.background=element_blank(),
        panel.border = element_blank(),
        plot.background=element_blank(),
        text = element_text(colour="white"),
        line = element_line(colour="white")) +
  theme()

grid.newpage()
grid.draw(g)
print(p, newpage = FALSE)