Skip to content
Prev 347889 / 398500 Next

color heatmap according to value ranges

Hi:

You get a gradient for your response variable because it is numeric.
You need to convert it to factor. (Discrete color sets need to be
mapped to discrete variables - a factor is one way to generate a
discrete variable.)  Here is one approach to get what you appear to be
looking for.

DF <- data.frame(a = rep(1:3, each = 3),
                 b = 1:3, d = 1:9)
DF$e <- cut(DF$d, c(0, 2, 3, 5, 10), rightmost = TRUE,
             labels = c("1-2", "2-3", "3-5", ">5"))

library(ggplot2)
ggplot(DF, aes(x = a, y = b, fill = e)) +
   geom_tile() +
   scale_fill_manual(values = c("darkblue", "blue", "lightblue", "white"))

You need a border of some kind around the plot since the right side of
the graph is the same color as the default background. If you're OK
with the default graph above, that's fine. If you want to expand it to
the edges, you need to draw your own border, something like

ggplot(DF, aes(x = a, y = b, fill = e)) +
   geom_tile() +
   scale_fill_manual(values = c("darkblue", "blue", "lightblue", "white")) +
  # eliminate the padding from each scale
   scale_x_continuous(expand = c(0, 0)) +
   scale_y_continuous(expand = c(0, 0)) +
 # draw the border
   theme(panel.border = element_rect(colour = "black", fill = NA))

The problem that remains is an inability to distinguish the legend key
color in the last category from the plot background. The simplest
workaround is to change the color of the last category in the scale
specification - one suggestion is a light gray, but you can always
substitute another color:

ggplot(DF, aes(x = a, y = b, fill = e)) +
   geom_tile() +
   scale_fill_manual(values = c("darkblue", "blue", "lightblue", "grey90")) +
   scale_x_continuous(expand = c(0, 0)) +
   scale_y_continuous(expand = c(0, 0)) +
   theme(panel.border = element_rect(colour = "black", fill = NA))

Dennis
On Fri, Feb 6, 2015 at 7:13 AM, <N.Hubner at ncmls.ru.nl> wrote: