r - 在 ggplot2 中自定义 "scale_color_gradient2"

标签 r ggplot2

我想在我的图像图中使用我自己的特定颜色。我是 ggplot2 的新手,所以从 here 看了一下它的手册并试图重复一些东西;但我不知道如何提供我的颜色条,就像我为图形绘图所做的那样。

library(reshape2)
library(ggplot2)

#my specific color list
mycol <- vector(length=512, mode = "numeric")
for (k in 1:256) mycol[k] <- rgb(255, k - 1, k - 1, maxColorValue=255)
for (k in 257:512) mycol[k] <- rgb(511 - (k - 1), 511 - (k - 1), 255, maxColorValue=255)
mycol <- rev(mycol)
ncolors <- length(mycol)

# graphics plot
par(mar = c(5, 13, 1, 6))
image(1:ncol(volcano), 1:nrow(volcano), t(volcano), zlim = c(0, ncolors), col=mycol, axes=FALSE, main="W Matrix", sub = "", xlab= "Components", ylab="Genes")
axis(2, at=1:nrow(volcano), labels=row.names(volcano), adj= 0.5, tick=FALSE, las = 1, cex.axis=0.25, font.axis=1, line=-1)
axis(1, at=1:ncol(volcano), labels=colnames(volcano), adj= 0.5, tick=FALSE,las = 3, cex=1, cex.axis=0.5, font.axis=1, line=-1)


# ggplot2
library(reshape2)
library(ggplot2)
library(ez)
ggplot(melt(volcano), aes(x=Var1, y=Var2, fill=value)) + geom_tile() + scale_color_gradient2(low = muted("red"), mid = "white", high = muted("blue"), midpoint = 0, space = "rgb", guide = "colourbar") # the code does not really use my color bar

*单位错误(tic_pos.c,“mm”):“x”和“单位”的长度必须> 0*

最佳答案

只是为了澄清@Didzis 的答案,它有效但可能不会产生您正在寻找的渐变......

'midpoint' 是指您希望由 'mid' 指定的颜色出现的数值。因此,与其将 'midpoint' 参数设置为 256(超出 value 的范围,这是您要着色的向量),而是将其设置为介于范围中间的某个值是明智的您正在着色的值,否则您不会使用您用“低”和“高”指定的整个渐变,这违背了 scale_color_gradient2 的目的.确切的值取决于您试图通过视觉传达的内容,但通常使用平均值或中位数。在这里,我编辑了@Didzis 的代码,将“中点”设置为 value 的中位数

v <- melt(volcano)
ggplot(v, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile() + 
  scale_fill_gradient2(low = "#0000FF", mid = "#FFFFFF", high ="#FF0000", 
                       midpoint = median(v$value), space = "rgb", guide = "colourbar")

这给出了一个具有更宽梯度的图:

enter image description here

关于r - 在 ggplot2 中自定义 "scale_color_gradient2",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17864233/

相关文章:

r - 从数据框中查找到特定位置最近的城市

r - 将大型 .txt 文件 (7.7 GB) 读入 R 的打包建议

r - 在 R 中使用 ggplot2 更改图例中的颜色

r - 使用 ggplot 进行函数式编程

r - 使用 GGplot R 组合来自 2 个不同数据帧列表和 1 个数据帧的数据以创建图表列表

r - ggvis 中的 Position_fill 函数是否等效?

r - 如何将 cuminc 函数与 ggplot2 相匹配

r - dist 函数的第 N 个最小对

r - xts 对象以周频率滞后 1 年

r - knitr 子文档中的引用书目