首页 > 解决方案 > 从 R 中的十六进制代码颜色表创建热图

问题描述

我有一个十六进制代码颜色表(“my_table”),如下:

   V1     V2

1 #010000 #080000

2 #140004 #000000

3 #000000 #080000

4 #040000 #110000

5 #050000 #080004

6 #030000 #030000

7 #090000 #0B0000

8 #3A0010 #2D000D

9 #000000 #000000

我想在 R 中绘制热图,在我的图中显示这些颜色。我试过了:

grid.raster(my_table, interpolate=FALSE)

它有效,但我也希望热图有标签、图例等,所以我想我会使用一个有更多选项的函数,比如 ggplot 来绘制我的热图。我找不到任何方法将这个十六进制代码矩阵绘制为 ggplot 的颜色,有人知道解决方案吗?

标签: rggplot2heatmaprgbraster

解决方案


要将数据框的一种“文字转录”转换为热图,您可以使用scale_fill_identity. 您的颜色有点暗,难以辨认,但绘制数据看起来像这样:

library(ggplot2)
library(dplyr)
library(tidyr)

my_table %>%
  tibble::rownames_to_column() %>%
  mutate(rowname = as.numeric(rowname)) %>%
  pivot_longer(-1) %>%
  ggplot(aes(x = name, y = rowname, fill = value)) +
  geom_tile(color = "gray50") +
  scale_fill_identity() +
  scale_x_discrete(position = "top") +
  scale_y_reverse(breaks = seq(nrow(my_table))) +
  coord_equal()

你说你想要一个图例,但不清楚图例实际上会显示什么,因为这些值是实际颜色,并且将十六进制字符串映射到图例中的颜色似乎没什么意义。当然,除非您的数据结构实际上比您问题中的数据结构复杂一些。


数据

my_table <- structure(list(V1 = c("#010000", "#140004", "#000000", "#040000", 
"#050000", "#030000", "#090000", "#3A0010", "#000000"), V2 = c("#080000", 
"#000000", "#080000", "#110000", "#080004", "#030000", "#0B0000", 
"#2D000D", "#000000")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9"))

推荐阅读