Search code examples
rggplot2plotgraphicsgradient

Translate base R plot to ggplot. Gradient fill rectangles


Could someone help me translate the following base R code to ggplot2:

EDIT - my x values are observations. For example:

x            <-runif(100,min=0,max=60)
lim_x        <-range(x)
lim_y        <-c(0.5,3.5)
probabilities<-cbind(seq(from=0,to=1,length.out=100),
                     c(seq(from=0,to=1,length.out=50),seq(from=1,to=0,length.out=50)),
                     seq(from=1,to=0,length.out=100))

plot(c(lim_x[1],lim_x[2]), c(lim_y[1], lim_y[2]), type = "n",ylab="",xlab="") 


for(i in 1:ncol(probabilities)){
  p <- probabilities[,i]
  gradient.rect(lim_x[1],i-0.5,lim_x[2],i+0.5,nslices=nrow(probabilities),
                reds=1,greens=1-p,blues=1-p)
}

which produces this plot:

enter image description here


Solution

  • This is how I would translate that base R code to ggplot2:

    library(ggplot2)
    
    lim_x        <-c(0,60)
    lim_y        <-c(0.5,3.5)
    probabilities<-cbind(seq(from=0,to=1,length.out=100),
                         c(seq(from=0,to=1,length.out=50),seq(from=1,to=0,length.out=50)),
                         seq(from=1,to=0,length.out=100))
    
    
    df <- reshape2::melt(probabilities)
    
    ggplot(df, aes(Var1, Var2, fill = value)) +
      geom_tile() +
      scale_fill_gradientn(colours = c("white", "red")) +
      annotate("rect", xmin = min(df$Var1) - 0.5, xmax = max(df$Var1) + 0.5,
               ymin = unique(df$Var2) - 0.5, ymax = unique(df$Var2) + 0.5,
               colour = "black", fill = NA)
    

    Created on 2021-09-14 by the reprex package (v2.0.1)

    Alternatively, if you want the exact same colours, you can use:

    ggplot(df, aes(Var1, Var2)) +
      geom_tile(aes(fill = I(rgb(1, 1 - value, 1 - value)))) +
      annotate("rect", xmin = min(df$Var1) - 0.5, xmax = max(df$Var1) + 0.5,
               ymin = unique(df$Var2) - 0.5, ymax = unique(df$Var2) + 0.5,
               colour = "black", fill = NA)