ASH.K
ASH.K

Reputation: 39

Coloring Cells of a Data.Frame R

I have this dataframe (shown below) and I am interested in plotting a a table like graph with colored cells

sample<- data.frame(c("k","k","k","k"), c("s","t","s","s"), c("t","n","t","t"), 
                   c("c","c","t","c"), c("n","c","c","c"))
rownames(sample)<- c("g1", "g2", "g3", "g4")
colnames(sample)<- c(10, 13, 20, 21, 25)    

I have found some previously answered questions here (such as: Conditional coloring of cells in table) and have tried the suggestions given there. Below is a sample of the code I ran:

#run ggplot2 suggestion by Drew Steen
sample$gene<- row.names(sample)
dfm<- melt(sample, id.vars="gene")
p <- ggplot(dfm, aes(x=variable, y=gene, label=value, fill=as.factor(value))) + 
  geom_text(colour="black") +
  geom_tile(alpha=0.5)
p    

However, this is not exactly the color scheme I am looking for. I need the plot to follow guidelines provided by another dataframe described below:

data<- data.frame(c("K", "s", "t", "c", "c"), c(10, 13, 20, 21, 25))
colnames(data)<- c("type", "position")    

So, for example, in sample$"13", I need all "s" to show up as one color, and all other values that is not "s" to show up as a different color. I need this to be done on all columns of sample based on the guidelines provided by data.

Upvotes: 1

Views: 1625

Answers (1)

MrFlick
MrFlick

Reputation: 206167

How about adding a new column to dfm indicating if a particular variable/value combination is in data?

dfm$ismatch<-ifelse(
    with(dfm,interaction(variable, value)) %in% 
      with(data, interaction(position,type)),
    "match","nomatch")

Then we can color based on this value

ggplot(dfm, aes(x=variable, y=gene, label=value, fill=ismatch)) + 
    geom_text(colour="black") +
    geom_tile(alpha=0.5)

and that gives

resulting plot

Upvotes: 1

Related Questions