4

I'm plotting a continuous variable using ggplot and geom_tile. By default, it plots using a continuous color bar. Something like this,

data <- cbind(ID = 1:100, a = runif(100, 0, 1), b = runif(100, 0, 1), c = runif(100, 0, 1))
data <- as.data.frame(data)
data <- melt(data, id.vars = "ID")
colnames(data) <- c("ID", "Parameter", "Value")

p <- ggplot(data, aes(y = ID, x = Parameter)) + geom_tile(aes(fill = Value))
print(p)

This produces the following plot.

Resulting plot

Now, what I'd actually like is for the colours to correspond to discrete, irregular intervals. For example, [0, 0.2) is red, [0.2, 0.5) is blue, and [0.5, 1.0] is purple. I expect that it's quite simple, but I can't seem to figure out how to achieve this. Any suggestions?

Dan
  • 11,370
  • 4
  • 43
  • 68
  • Does this question help? http://stackoverflow.com/questions/18487369/ggplot-set-scale-color-gradientn-manually – David Robinson Sep 02 '15 at 21:12
  • 4
    This sounds like a job for `cut` or `Hmisc::cut2` or equivalent. Code could look something something like `aes(fill = cut(Value, breaks = c(0, .2, .5, 1), include.lowest = TRUE))`, followed by setting colors/legend name in `scale_fill_manual`. – aosmith Sep 02 '15 at 21:32

1 Answers1

2

Thanks to @aosmith for the solution. Here's the code, in case it is of use to someone.

p <- ggplot(data, aes(y = ID, x = Parameter)) 
p <- p + geom_tile(aes(fill = cut(Value, breaks = c(0, .2, .5, 1), include.lowest = TRUE)))
p <- p + scale_fill_manual(values = c("red", "blue", "green"),
                           labels = c("[0, 0.2)", "[0.2, 0.5)", "[0.5, 1.0]"),
                           name = "Stuff")
print(p)

This produces the following plot.

Resulting plot

Dan
  • 11,370
  • 4
  • 43
  • 68