Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot, geom_tile: plot continuous variable using irregular, user-defined, discrete intervals

Tags:

r

ggplot2

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?

like image 877
Lyngbakr Avatar asked Sep 06 '25 19:09

Lyngbakr


1 Answers

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

like image 101
Lyngbakr Avatar answered Sep 10 '25 14:09

Lyngbakr