Question

I have to produce a plot using R and don't know how I can do it. Imagine the following:

sample_names = c("a","b","d","e","f","g","h","i","l","m")
M = cbind(seq(0,1,length.out=10), c(1,1,1,1,2,2,2,3,3,3))

M is a 2 columns matrix where the first column is a continuous measurement, and the second column is a label associated to the measurement (e.g. 1 is for "low", 2 is for "medium", 3 is for "high").

What I want to create is basically a vertical colorbar with labels both on the left and on the right. The colors should represent the values of the continuous measurements. The labels on the left are the sample names, the labels on the right the corresponding "low","medium", "high" labels for the data.

Possibly I would like the colors to range from green (0) to red (1) with dark colors around 0.5.

How can I possibly plot such a graph using R?

Was it helpful?

Solution

Here is a solution using ggplot2:

levels <- c('low','med','high')
df <- data.frame(
    sample = c("a","b","d","e","f","g","h","i","l","m"),
    value = seq(0,1,length.out=10),
    level = factor(levels[c(1,1,1,1,2,2,2,3,3,3)], level=rev(levels))
)    

# require(ggplot2)
# require(grid)
ggplot(data=df, aes(x=TRUE, y=sample, fill=value)) + geom_tile() +
scale_fill_gradientn(colours=c('green','black','red')) + 
facet_grid(level~., scales='free', space='free') +
scale_y_discrete(expand=c(0,0)) +
theme(panel.margin=unit(0.1,'mm'), axis.title=element_blank(), 
      axis.text.x=element_blank(), axis.ticks.x=element_blank(), 
      legend.title=element_blank())

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top