简体   繁体   English

具有两个向量的R着色数据帧

[英]R coloring data frame with two vectors

Suppose I have two vectors of the same length, one filled with colors, and another filled with letters. 假设我有两个长度相同的矢量,一个矢量填充颜色,另一个矢量填充字母。

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

What would be the best direction to go about creating a heatmap of sorts, of two rows, where the first row contains each letter, and the next row is a box colored in with the numerically corresponding vector index? 创建两行排序的热图的最佳方向是什么,其中第一行包含每个字母,下一行是一个用数字表示的矢量索引着色的框?

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

I would like to output this diagram with ggplot but unlike with a heatmap in ggplot, there would be many different colors for many different variables. 我想用ggplot输出此图,但与ggplot中的热图不同,许多不同的变量会有许多不同的颜色。

I'd do it in ggplot2. 我会在ggplot2中做到这一点。

First you need to make colors and letters into an factor, so that the associated orders are preserved. 首先,您需要使颜色和字母成为一个因素,以便保留关联的顺序。

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

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

Then you create your own fill palette. 然后创建自己的填充调色板。 Just the same as your colours. 与您的颜色一样。

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

Now use geom_raster to make the heatmap and geom_text to place the letters and add your own fill scale. 现在,使用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)

Is this what you want? 这是你想要的吗? It will require a bit of tweaking for repeated colours. 对于重复的颜色,将需要进行一些调整。

Also in ggplot: 也在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="")

在此处输入图片说明

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

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