ggplot热图的反色啤酒颜色

时间:2019-11-07 21:13:26

标签: r ggplot2 heatmap colorbrewer

library(tidyverse)
library(RColorBrewer)
x <- LETTERS[1:20]
y <- paste0("var", seq(1, 20))
data <- expand.grid(X = x, Y = y)
data$Z <- runif(400, 0, 5)

如果我在上面构造了数据框,然后用下面的代码绘制了一个热图,那么我将得到:

ggplot(data, aes(X, Y, fill = Z)) + 
  geom_tile() +
  scale_fill_distiller(palette = "Reds") +                    # line 3
  # scale_fill_distiller(palette = "Reds", direction = -1) +  # line 4
  labs(x = NULL, y = NULL) +
  theme_minimal()

根据line #4,我认为运行line #3代替?scale_fill_distiller()(以上)应该颠倒了我的传奇色彩:

  

direction参数:设置刻度中颜色的顺序。如果为1,则默认为RColorBrewer :: brewer.pal()输出的颜色。如果为-1,则颜色顺序相反。

实质上,热图的白色区域将变为深红色,而热图的深红色区域将变为白色。为什么不发生这种情况?在上方运行line #3line #4,输出将相同。

heatmap

1 个答案:

答案 0 :(得分:2)

在上面我的评论中,让我们将两个图并排放置

gg1 <- ggplot(data, aes(X, Y, fill = Z)) +
    geom_tile() +
    scale_fill_distiller(palette = "Reds", direction = +1) +
    labs(x = NULL, y = NULL) +
    theme_minimal()

gg2 <- ggplot(data, aes(X, Y, fill = Z)) +
    geom_tile() +
    scale_fill_distiller(palette = "Reds", direction = -1) +
    labs(x = NULL, y = NULL) +
    theme_minimal()

library(gridExtra)
g <- grid.arrange(gg1, gg2)

enter image description here

您在上面看到的行为的原因是由于scale_fill_distiller默认假定direction = -1

scale_fill_distiller
#function (..., type = "seq", palette = 1, direction = -1, values = NULL,
#    space = "Lab", na.value = "grey50", guide = "colourbar",
#    aesthetics = "fill")
#{
#    type <- match.arg(type, c("seq", "div", "qual"))
#    if (type == "qual") {
#        warning("Using a discrete colour palette in a continuous scale.\n  Consider using type = \"seq\" or type = \"div\" instead",
#            call. = FALSE)
#    }
#    continuous_scale(aesthetics, "distiller", gradient_n_pal(brewer_pal(type,
#        palette, direction)(7), values, space), na.value = na.value,
#        guide = guide, ...)
#}
#<bytecode: 0x7fed742ed1d8>
#<environment: namespace:ggplot2>