5

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))
Henrik
  • 65,555
  • 14
  • 143
  • 159
Dieter Menne
  • 10,076
  • 44
  • 67
  • 1
    [This](https://stackoverflow.com/questions/30902515/how-to-rotate-an-image-r-raster) can be a good reference, I think. – jazzurro Feb 03 '18 at 11:54

1 Answers1

10

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

pogibas
  • 27,303
  • 19
  • 84
  • 117