rggplot2scalecolorbrewer

How can I create a specific color gradient scale for my heatmap?


I would like to create this color scale for my heatmap:

  1. [0-49] -> dark green

  2. [50-99] -> green

  3. [100-149] -> light green

  4. [150-199] -> yellow

  5. [200-299] -> orange

  6. [300-…] -> red

Here is a sample of my dataset:

Dataset

I've already tried the code below but it doesn't work:

colfunc <-colorRampPalette(c("darkgreen", "lightgreen", "yellow", "orange", "red"))
ggplot(DATASET, aes(x = BUS_NR, y = MONTH_NR, fill = factor(ALERT_NB)) +
  geom_tile() +
  scale_fill_manual(values = colfunc(300))

Solution

  • The key is to define a function which creates a new column in your dataset defining the class of the color (in my case z). Then you can simply map the color to the class and plot it. Please provide an example dataset next time. Took quite a bit to figure out but works now:

    library(ggplot2)
    x <- 1:10
    y <- x*x*x
    df <- data.frame(x,y)
    cols <- c("1"="darkgreen","2"="green", "3"="lightgreen", "4" = "yellow", "5"="orange", "6"="red")
    
    classof <- function(a){
      if (a<50){
        return(1)
      }
      if (a<100){
        return(2)
      }
      if (a<150){
        return(3)
      }
      if (a<200){
        return(4)
      }
      if (a<300){
        return(5)
      }
      else {
        return(6)
      }
    }
    z <- c()
    for (i in seq(1,length(y))){
      z <- c(z,classof(y[i]))
    }
    
    df$z <- z
    
    p <- ggplot(df, aes(x,y))+ geom_point(aes(colour = factor(z)))
    p + scale_colour_manual(values=cols)