1

I have the following code to create color bars, modified from here:

color.bar <- function(lut, title='') {
    min <- -1
    max <- -min
    nticks <- 5
    ticks <- seq(min, max, len=nticks)
    scale <- length(lut)/(max-min)
    pdf(NULL)
    dev.control(displaylist="enable")
    plot(c(min,max), c(10,0), type='n', bty='n', xaxt='n', xlab='', yaxt='n', ylab='', main=title, cex.main=3)
    axis(1, ticks, las=1, labels=c('MIN','','','','MAX'), cex.axis=2)
    for (i in 1:length(lut)) {
      x = (i-1)/scale + min
      rect(x, 0, x+1/scale, 10, col=lut[i], border=NA)
    }
    P <- recordPlot()
    invisible(dev.off())
    return(P)
}

myplot <- color.bar(colorRampPalette(c("light green", "yellow", "orange", "red"))(100), "Intensity")
myplot

Which produces the following:

test

Now what I would need would be to do the exact same in ggplot2, cause I want to add the result, along with a list of ggplots, to a pdf using grid.arrange.

I do not really know how to start... Anybody can help me get started to produce the same output using ggplot2?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
DaniCee
  • 2,397
  • 6
  • 36
  • 59
  • 1
    Do you really need to reproduce this using ggplot2? `plot_grid` from the cowplot package has similar functionalities to `grid.arrange` from gridExtra, and can handle objects of the recordedplot class, in addition to normal ggplot objects. See [here](https://cran.r-project.org/web/packages/cowplot/vignettes/plot_grid.html). – Z.Lin Feb 21 '19 at 11:04
  • Alright let me look into `plot_grid` and `ggarrange` to see if I can mix this bar plot with my ggplots and get back to you\ – DaniCee Feb 22 '19 at 02:07
  • OK! I can save the color bars with `grid.grab()` or `recordPlot()` and use `plot_grid`! – DaniCee Feb 22 '19 at 07:10
  • Awesome! Glad that solved your problem :) – Z.Lin Feb 22 '19 at 10:11

0 Answers0