【问题标题】:extract color hex value from continuous scale ggplot legend从连续比例ggplot图例中提取颜色十六进制值
【发布时间】:2020-05-14 03:38:33
【问题描述】:

给定一个数值,我试图在 ggplot 图例中找到相应的颜色;本质上是相反的传说。我将尝试一个简化的激励示例:

df <- data.frame(x = rnorm(11, mean = .2, sd = .1), y = rnorm(11, mean = -.2, sd = .2))

现在绘制数据

d <- ggplot(df, aes(x, y)) + 
       geom_point() + 
       geom_raster(aes(fill = seq(from = -1, to = 1, by = .2)))
d

我现在想知道图例中 0.2 处的值对应的十六进制颜色代码(或对 -1,1 范围内的任何其他值执行此操作)。我意识到对于这个例子,这似乎有点傻。实际上,我为科学图像制作了一个共享图例,我需要从图例中向后提取十六进制颜色。

我尝试使用 g_legened() 提取图例;但是,数据结构很复杂,我被卡住了。

library(lemon)
legend <- g_legend(d)

设想的功能是hexColor &lt;- reverseLegend(legend,.2),我们将不胜感激。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    最简单的方法可能是首先手动定义颜色。以下线程有帮助:

    For assigning the colors to the values

    To manually create the color sequence

    注意我使用了geom_tile 而不是geom_raster。此外,我使用了scale_fill,而不是在aes 中使用向量——这样您就不会创建一些可能与您的数据无关的图例。另外我在scale_fill中设置了limits

    我打算寻找一种方法来查找颜色值 - 但这可能是最直接的选择。

    library(ggplot2)
    
    df <- data.frame(x = rnorm(11, mean = .2, sd = .1), y = rnorm(11, mean = -.2, sd = .2))
    
    vec_break <- seq(-1,1,0.2) #use any sequence
    colfunc <- grDevices::colorRampPalette(c("light blue", "dark blue")) # the choice of colors is yours!
    vec_col <- colfunc(length(vec_break))
    
    ggplot(df, aes(x, y)) + 
      geom_tile(aes(fill = y)) +
      scale_fill_gradientn(breaks = vec_break, colors = vec_col, limits = c(-1,1))
    
    

    reprex package (v0.3.0) 于 2020-01-28 创建

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 2014-02-18
      • 2011-02-01
      • 1970-01-01
      • 2012-11-04
      • 2020-03-05
      相关资源
      最近更新 更多