R: ggplot background gradient coloring

雨燕双飞 提交于 2020-05-25 07:42:06

问题


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)


来源:https://stackoverflow.com/questions/39632445/r-ggplot-background-gradient-coloring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!