0

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))
M--
  • 25,431
  • 8
  • 61
  • 93
  • It's hard to answer this well without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)—a sample of data would make it clear what you're working with – camille Oct 07 '19 at 13:58
  • Hi Camille I've updated my post with the dataset ! :) –  Oct 08 '19 at 08:50
  • Click the link in my comment. There are examples of ways to include samples of data that we can load into R, i.e. not pictures of tables – camille Oct 08 '19 at 14:29
  • Sorry @camille ! I'm new on stack overflow ! I'm still learning how it works ! I could make the exercice with cut() and I also discovered the scale_fill_gradientn() function yesterday and I really love it ! Thanks a lot for your time and your help ! Have a nice day ! –  Oct 10 '19 at 08:37

1 Answers1

0

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)
benschbob91
  • 155
  • 12
  • I'll try to apply this to my heatmap ! –  Oct 07 '19 at 13:32
  • 1
    You don't need to define a function to do this: `cut` is a base function that will take a vector of breaks. Also keep in mind that since R is a vectorized language, you don't need `for` loops to apply a function along a vector, and building up a vector by binding each iteration in this way becomes expensive – camille Oct 07 '19 at 13:57
  • I've already tried it and it works perfectly ! Thanks again for your help @ benschbob91 ! –  Oct 07 '19 at 14:20
  • Hi @camille how can I replace the function "classof" with cut(), please ? Thanks ! –  Oct 08 '19 at 11:59
  • In your case it should be: cut(y, breaks=c(50,100,150,200,300)) – benschbob91 Oct 08 '19 at 13:31