简体   繁体   English

为Data.Frame R的单元格着色

[英]Coloring Cells of a Data.Frame R

I have this dataframe (shown below) and I am interested in plotting aa 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. 我在这里找到了一些先前回答的问题(例如: table中单元格的有条件着色 ),并尝试了那里给出的建议。 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. 因此,例如,在sample$"13" ,我需要所有“ s”显示为一种颜色,而所有其他非“ s”值显示为不同的颜色。 I need this to be done on all columns of sample based on the guidelines provided by data . 我需要根据data提供的准则在sample的所有列上执行此操作。

How about adding a new column to dfm indicating if a particular variable/value combination is in data? 如何在dfm添加新列,以指示数据中是否存在特定的变量/值组合?

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 那给

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM