R: ggplot background gradient coloring

2020-06-19 16:03发布

I would like to generate ggplot’s with gradient coloring, filling both plot panel and its background, as herein shown.

enter image description here

As you can see the gradient background coloring encompasses both plot panel and its background. At the moment, only an "approximation" of the required solution is known to me:

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

Using aboveshown code, the plot panel results as gradient colored within axis boundaries, however it does not span the overall background with such gradient coloring. The theme(plot.background =...) is capable to fill the remaining background, however it does not seem to be able to take advantage of gradient coloring. To remark further that same gradient coloring should be applied to the overall plot background.

Any suggestions will be appreciated. Thanks.

1条回答
贼婆χ
2楼-- · 2020-06-19 16:19

you can print/draw the plot on top of a 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)
查看更多
登录 后发表回答