在R中使用十六进制值绘制图表颜色

12

如何在R中生成一个5x5的矩阵,使每个单元格都使用来自调色板(例如viridis)的不同颜色进行着色,并且每个单元格显示颜色的十六进制值?感谢您的帮助!


4
我标记了重新开放这个问题。我认为它并不缺乏焦点,实际上非常具体。这也是一个非常有趣的问题。 - tjebo
2个回答

30
你可以使用{{scales}}包中的{{show_col}}函数。
library(viridis)
library(scales)

nCol <- 25
myCol <- viridis(n = nCol)
myCol
#>  [1] "#440154FF" "#471164FF" "#481F70FF" "#472D7BFF" "#443A83FF"
#>  [6] "#404688FF" "#3B528BFF" "#365D8DFF" "#31688EFF" "#2C728EFF"
#> [11] "#287C8EFF" "#24868EFF" "#21908CFF" "#1F9A8AFF" "#20A486FF"
#> [16] "#27AD81FF" "#35B779FF" "#47C16EFF" "#5DC863FF" "#75D054FF"
#> [21] "#8FD744FF" "#AADC32FF" "#C7E020FF" "#E3E418FF" "#FDE725FF"
show_col(myCol)

myCol <- viridis(n = nCol, option = "E")
show_col(myCol)

myCol <- viridis(n = nCol, option = "B" )
pie(rep(1, nCol), col = myCol, labels = myCol)

这段文字是关于2018年8月15日使用reprex包(v0.2.0.9000)创建的。


5

ggplot2中的scale_fill_identity()可以使用包含十六进制值的列并将其解释为颜色。如果要允许组合不同的调色板:

library(RColorBrewer)
library(tidyverse)
library(foreach)
library(reshape2)

# Matrix of colors ----
# specify
palettes <- c("BrBG", "PiYG", "PuOr", "RdBu", "RdGy")
n_colors <- 5

# take colors, name the column, then cbind
color_mat <- foreach(p = palettes, .combine = "cbind") %do% {
  tibble(!!p := brewer.pal(n_colors, p))
}



# Plotting -----
# reshape for plotting:
color_df <- mutate(color_mat, order = 1:n())
long_color <- melt(color_df,
                   id.vars = "order",
                   variable.name = "palette",
                   value.name = "color")


# plot it, using scale_color_identity to interpret the hex as a color
ggplot(long_color, aes(x = palette, y = order, fill = color)) +
  geom_tile() +
  geom_text(aes(label = color)) +
  scale_fill_identity()

这段内容是在2018年08月15日由reprex package(v0.2.0)创建的。


谢谢!我已经寻找类似于scale_fill_identity()的东西好几个小时了! - Harry M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接