-->

R: ggplot background gradient coloring

2020-06-19 16:32发布

问题:

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

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:

you can print/draw the plot on top of a rasterGrob,

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)