Change orientation of grob background gradient

时间:2018-02-03 10:59:55

标签: r ggplot2 background-image

I was surprised that the following simple grob created from a vector of colors works almost as requested.

enter image description here

However, I would like to make the gradient left to right, not top to bottom.

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

1 个答案:

答案 0 :(得分:7)

Answer is t

You have to transpose your grad vector (input to rasterGrob):

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

enter image description here