用R中的十六进制值绘制颜色[关闭]

问题描述 投票:3回答:2

如何在R中生成5x5矩阵,每个单元格以不同于调色板(例如绿色)的颜色着色,每个单元格显示颜色的十六进制值?谢谢您的帮助!

r
2个回答
6
投票

您可以使用show_col包中的scales函数

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)

reprex package创建于2018-08-15(v0.2.0.9000)。


2
投票

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()

reprex package创建于2018-08-15(v0.2.0)。

© www.soinside.com 2019 - 2024. All rights reserved.