改变 grob 背景渐变的方向

Change orientation of grob background gradient

令我惊讶的是,以下从颜色矢量创建的简单 grob 几乎可以按要求工作。

但是,我想使渐变从左到右,而不是从上到下。

library(ggplot2) 
library(grid)
grad = colorRampPalette(c("red", "yellow"))(10)

ggplot(df, aes(x,y)) + 
  annotation_custom(rasterGrob(grad, 
                        width=unit(1,"npc"), 
                        height=unit(1,"npc"))) +
  scale_x_continuous(limits = c(0,1)) +
  scale_y_continuous(limits = c(0,1))

答案是t

您必须转置您的 grad 向量(输入到 rasterGrob):

library(ggplot2)
ggplot() + 
    annotation_custom(rasterGrob(t(grad), 
                                 width = unit(1, "npc"), height = unit(1, "npc")))