2015-07-21 54 views
0

假设我有两个长度相同的矢量,一个填充颜色,另一个填充字母。R具有两个矢量的着色数据帧

colors <- c("red","white","blue","green","yellow") 
letters <- c("A","B","C","D",E") 

什么是最好的方向去创造各种各样的热图,两排,其中第一行包含每个字母,而下一行是与数字对应的矢量指数有色在一个盒子里?

----------- 
|A|B|C|D|E| 
----------- 
|R|W|B|G|Y|  #<---- Colored boxes, not just characters. 
----------- 

我想输出将此图与ggplot但不像在ggplot热图,会有很多不同的颜色为许多不同的变量。

+0

在你有什么想对色灯箱? – 2015-07-21 09:33:41

+1

R Shiny or ggplot would be .. – ALKI

+0

请编辑您的问题,使其更清晰。 – 2015-07-21 09:35:53

回答

2

我会在ggplot2中做到这一点。

首先,您需要将颜色和字母变成一个因子,以便保留关联的订单。

colors <- c("red","white","blue","green","yellow") 
letters <- c("A","B","C","D","E") 

colors <- factor(colors, levels = colors) 
letters <- factor(letters, levels = letters) 

然后你创建你自己的填充调色板。跟你的颜色一样。

my_fill <- c("red", "white", "blue", "green", "yellow") 

现在使用geom_raster,使热图和geom_text放置信件,并添加自己的填充缩放。

ggplot(NULL) + 
    aes(x = c(1, 2, 3, 1, 2), 
     y = c(2, 2, 2, 1, 1), 
     fill = colors, 
     label = letters) + 
    geom_raster() + 
    geom_text() + 
    scale_fill_manual(values=my_fill) 

这是你想要的吗?它需要对重复颜色进行一些调整。

1

而且在ggplot:

library(ggplot2) 


#make data 
colors = c("red","white","blue","green","yellow") 
names(colors) <- c("A","B","C","D","E") 
data <- expand.grid(letters = c("A","B","C","D","E"),y=c(1:2), 
        stringsAsFactors = F) 
data$colour <- ifelse(data$y==1,colors[data$letters],"white") 
data$label <- ifelse(data$y==1,"",data$letters) 

#plot 
p1 <- ggplot(data, aes(x=letters,y=y)) + geom_tile(aes(fill=colour),colour="black")+ 
    scale_fill_identity() + coord_fixed() 
p1 + geom_text(aes(label=label)) + theme_minimal() + 
    theme(
    axis.text=element_blank(), 
    axis.ticks=element_blank(), 
    panel.grid=element_blank() 
) + labs(x="",y="") 

enter image description here

+0

啊,是的!我完全错了 - 现在我明白了这个问题 –