在 ggplot geom_tile 热图中反转连续色标图例

时间:2021-04-28 16:22:44

标签: r ggplot2 legend geom-tile

最小示例:

library(ggplot2)
x <- c(1:3)
y <- c(1:3)
data <- expand.grid(X=x, Y=y)
data$Z <- runif(9)
ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile()

产生这个:

plot

如何让右侧的 Z 比例尺从顶部的 0 运行到底部的 1?而不是从下到上?

我试图强调较小的值,如果可能的话,实际上希望它与 viridis 或 magma 配色方案一起使用。但是 direction=-1 上的 scale_fill_viridis 只会翻转色阶。想要黄色 = 0,蓝色/黑色 = 1。然后 Z 缩放从底部到顶部从蓝色到黄色。

ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile() +
  scale_fill_viridis(discrete=FALSE, direction=-1)

viridis

2 个答案:

答案 0 :(得分:0)

scale_fill_distiller 中,您可以选择调色板和调色板的方向。

library(ggplot2)
x <- c(1:3)
y <- c(1:3)
data <- expand.grid(X=x, Y=y)
data$Z <- runif(9)


ggplot(data) +
  aes(x = X, y = Y, fill = Z) +
  geom_tile(size = 1L) +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_minimal()

答案 1 :(得分:0)

我让它与 trans = 'reverse' 一起工作

ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile() + 
  scale_fill_viridis(trans = 'reverse', option="plasma")

enter image description here