R:ggplot背景渐变着色 [英] R: ggplot background gradient coloring

查看:289
本文介绍了R:ggplot背景渐变着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用上面显示的代码,绘图面板在轴边界内显示为渐变色,但是使用这种渐变色不会覆盖整个背景. theme(plot.background = ...)可以填充剩余的背景,但是它似乎无法利用渐变色.为了进一步说明,应该对整个绘图背景应用相同的渐变色.

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.

推荐答案

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

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)

这篇关于R:ggplot背景渐变着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆