【问题标题】:R - Create scale from RGB and number valuesR - 从 RGB 和数值创建比例
【发布时间】:2015-01-04 11:53:52
【问题描述】:

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

示例数据:

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 颜色来实现。

【问题讨论】:

    标签: r legend heatmap


    【解决方案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()
    

    给我这个

    您可以使用函数colorRampPalette 绘制一个颜色条并根据您的需要进行调整。

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

    代码:

    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))])
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多