R - 从RGB和数值创建比例

时间:2014-11-07 16:16:07

标签: r legend heatmap

我有一个包含值及其相应RGB值的表。问题是我缺少一个图例,我需要看起来像这样(只有表中相应的RGB值):

Legend

示例数据:

7.14285714285715 "73,0,0"
-5.76923076923077 "108,0,0"
-1.61290322580645 "214,0,0"
8.33333333333334 "42,0,0"
7.75862068965517 "57,0,0"
-2.38095238095238 "194,0,0"
4.96183206106871 "128,0,0"
-0.442477876106196 "244,0,0"
-4.54545454545455 "139,0,0"
3.84615384615385 "157,0,0"
-4.54545454545455 "139,0,0"
-8.94736842105263 "27,0,0"
-8.55855855855856 "37,0,0"
-3.6231884057971 "163,0,0"
-3.01204819277108 "178,0,0"
0.909090909090907 "232,0,0"
-7.14285714285715 "73,0,0"
-6.25 "96,0,0"
-0.862068965517238 "233,0,0"
-0.724637681159422 "237,0,0"

负数与正数具有相同的颜色(即-9 == 9)。我认为这可以通过绘制热图并为每个值分配自定义RGB颜色来实现。

1 个答案:

答案 0 :(得分:1)

使用符合我color.bar需求的here。您可以根据需要进行调整

pdf(file='~/desktop/tmp.pdf', height = 5, width = 6)
par(mar = c(5,5,2,5))
plot(1:5)
color.bar(c('black','orange','yellow'), 
          at.x = par('usr')[2], at.y = par('usr')[3])
text(par('usr')[2], y = par('usr')[3:4], pos = 4, labels = c(10, 0), xpd = NA)
mtext('Dispersion (%)', side = 4, line = 1)
dev.off()

给了我这个

enter image description here

您可以使用功能colorRampPalette绘制颜色条,只需适应您的需要。

plot(1:100, col = colorRampPalette(c('black','orange','yellow'))(100), pch = 19, cex = 2)

enter image description here

代码:

color.bar <- function(cols, x = NULL, y = x, labels = NULL,
                      at.x = par('usr')[2], at.y = par('usr')[3], 
                      cex.x = 1, cex.y = 1, ...) {

  op <- par(no.readonly = TRUE)
  on.exit(par(op))
  par(list(...))

  par(mar = c(5, 4, 4, 4) + .1, xpd = TRUE)
  bx <- par('usr')
  nc <- 1000
  cols <- colorRampPalette(cols)(nc)

  bx.y <- c(bx[3], bx[4])
  sapply(0:nc, function(x) {
    segments(at.x, 
             at.y + x * diff(bx.y) / nc * cex.y, 
             at.x + diff(bx[1:2]) / nc * 20 * cex.x, 
             at.y + x * diff(bx.y) / nc * cex.y, 
             col = cols[x], lwd = 1, xpd = TRUE)
  })
  if (!is.null(labels))
    text(x = at.x, y = pretty(y), labels = pretty(labels), 
         pos = 4, cex = .8, offset = .75)
  if (!is.null(x))
    invisible(cols[rescaler(x, c(1, nc))])
}