簡體   English   中英

如何知道 R 中某個命名顏色的 rgb 顏色代碼?

[英]How to know the rgb colour code for a certain named color in R?

在 ggplot2 plot 中,我想使用 function:

scale_fill_manual(
values = c(
'mediumorchid2',
'gold1',
'red'
)

我知道“紅色”的 RGB 代碼顏色:#FF0000

colors 'mediumorchid2' 或 'gold1' 也有這種代碼。 我怎么才能得到它?

gplots package 有一個名為col2hex()的 function :

library(gplots)
col2hex("gold1")
"#FFD700"

首先,你說的是十六進制表示,而不是 RGB。 RGB 表示是三個數字(介於 0 和 1 之間或介於 0 和 255 之間),分別給出紅色、綠色和藍色級別。

要獲得 RGB 表示,您可以只使用基數 function col2rgb()

col2rbg('mediumorchid2')
#       [,1]
# red    209
# green   95
# blue   238

長期以來,我一直有一個個人便利 function 來獲取十六進制表示,因為這是我需要經常做的一項任務:

col2hex <- function(x, alpha = "ff") {
    RGB <- col2rgb(x)
    return(apply(RGB, 2, function(C) {
        paste(c("#", sprintf("%02x", C), alpha), collapse = "")
    }))
}
col2hex('mediumorchid2')
# [1] "#d15feeff"

更新:

Gordon Shumway 的出色回答提到顯然已經有一個 package 和這樣一個 function。 我會推薦,但是。 對於 RGB 與十六進制的討論以及以防萬一您不想依賴gplot ,我都會留下我的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM