Home > OS >  Translate base R plot to ggplot. Gradient fill rectangles
Translate base R plot to ggplot. Gradient fill rectangles

Time:09-17

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

CodePudding user response:

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)

CodePudding user response:

You have to transform your data

probabilities_long <- matrix(t(probabilities), ncol = 1)

df <- data.frame(x1 = sort(rep(seq(0,60,length.out = 100),3)), 
                 x2 = sort(rep(seq(0.6, 60.6, length.out = 100),3)),
                 y1 = rep(c(0.5, 1.5, 2.5),100),
                 y2 = rep(c(1.5, 2.5, 3.5),100), 
                 prob = matrix(t(probabilities), ncol = 1))

Then you can use geom_rect to draw each tile:

ggplot(df) 
    geom_rect(aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill = prob)) 
    scale_fill_gradient(low = "#ffffff",
                          high = "#ff0000")
  • Related