【问题标题】:Setting up custom color scale in R在 R 中设置自定义色阶
【发布时间】:2016-10-03 23:54:12
【问题描述】:

我正在尝试在 R 中设置自定义比例。我的数据范围在 -5.4 到 +3.6 之间,我想将数据集中在 0(白色)附近。我想要一个数据比例,这样我在 0 上下都有相同数量的渐变(我目前正在拍摄 7)。我遇到的问题是我无法正确缩放比例,而且我不确定我的问题出在哪里。

我目前的代码(源数据在底部的 Pastebin 链接中):

   png('127-2_4_compare_other.png',width = 1200, height = 800, units = "px")
   colfunc <- colorRampPalette(c("blue", "white", "red"))
   f <- function(m) t(m)[,nrow(m):1]
   colorBarz=matrix(seq(-5.5,4,len=15),nrow=1)
   colorBarx=1
   source("127-2_4.CompareMatrix.txt")
   colorBary=seq(-5.4,3.6,len=15)
   cus_breaks=c(-5.400, -4.725, -4.050, -3.375, -2.700, -2.025, -1.350, -0.675,  0.45, 0.90, 1.35, 1.80, 2.25, 2.70, 3.15, 3.60)
   layout(matrix(c(1,2), 1, 2, byrow = TRUE), widths=c(9,1))
   image(f(Compare2and4),axes=FALSE,ylab="Amino acids",xlab="Position",main="Sample 2 vs. 4",col=colfunc(15),breaks=cus_breaks)
   axis(1, seq(from = 0, to = 1, by = 0.03703), labels=c(1:11,1:17))
   axis(2, seq(from = 0, to = 1, by = 0.0526),labels=rev(c("A","R","N","D","C","E","Q","G","H","I","L","K","M","F","P","S","T","W","Y","V")),las=2)
   image(colorBarx,colorBary,colorBarz,col=colfunc(15),axes=FALSE,xlab="",ylab="log(Sample4 / Sample2)",breaks=cus_breaks)
   axis(2,las=2)
   dev.off()

我正在寻找 0 到 3.6 以上的七个均分箱和 0 到 -5.4 以下的七个均分箱,我希望 0 打在白色箱的中间。此外,如果有人可以查看热图代码本身以确保没有明显的错误,我将不胜感激。 Pastebin of the source data

【问题讨论】:

  • 不确定它是否能解决您的问题,但在这种情况下,我倾向于对数据进行分类(例如使用cut)而不是调色板。
  • 如果我理解 cut 正确,那将帮助我设置大于 0 和小于 0 的大小相等的 bin。我想我在这里对 cus_breaks 做了同样的事情,尽管我看不正确?

标签: r colors visualization


【解决方案1】:

您提出的色阶存在一个问题,即色阶上每个点之间的感知距离不相等。相同的颜色距离是指与负端相比,正端的数据值范围更大。我建议不要重新发明轮子,而是利用 ggplot 的强大功能。

默认情况下,发散色标的中点为白色,值为 0。

例如:

Compare2and4_t <- t(Compare2and4)[,nrow(Compare2and4):1]
am_ac <- c("A","R","N","D","C","E","Q","G","H","I","L","K","M","F","P","S","T","W","Y","V")
pdat <- data.frame(x = 1:nrow(Compare2and4_t), 
                   y = factor(rep(am_ac, each = nrow(Compare2and4_t)), levels = rev(am_ac)),
                   val = c(Compare2and4_t))

library(ggplot2)
library(scales)

ggplot(pdat, aes(x, y, fill = val)) + 
  geom_tile() +
  scale_fill_gradient2(low = 'darkblue', high = 'darkred', 
                       limits = c(-5.4, 3.6), oob = squish) +
  coord_equal(expand = FALSE) +
  scale_x_continuous(breaks = unique(pdat$x)) +
  theme_classic() +
  labs(x = 'Position', y = 'Amino acids')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多