反转默认比例梯度ggplot2

Reversing default scale gradient ggplot2

我是新手,正在尝试设计热图。这是我的代码:

ggplot(gd, aes(Qcountry, Q6_1_Q6d), order = TRUE) +
  geom_tile(aes(fill = prob), colour = "white") +
  theme_minimal() +
  labs( y = "Main reason for mobility", x = "Country") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.3)) +
  scale_fill_gradient(name = "(%)")

这生成了一个完美的图表,我的问题是低水平是深蓝色,高价值是浅蓝色,这不直观。最常见的方法是使用 rev()。但就我而言,我不知道该怎么做。那么,是否可以反转此 默认比例 ? This is the legend

其他问题,有没有办法只用一种颜色创建比例渐变。我的意思是,scale_fill_gradient/scale_fill_gradientn 需要设置低色和高色 (low = "", high = "") 我想把蓝色换成红色。

非常感谢您的支持。

?scale_colour_gradient 显示 low = "#132B43"high = "#56B1F7" 的默认值。

只需切换一下:

ggplot(faithfuld, aes(waiting, eruptions)) +
    geom_raster(aes(fill = density)) +
    scale_fill_continuous(high = "#132B43", low = "#56B1F7")

就个人而言,我认为这不如默认设置直观。


或者,您可以使用反向比例,但这也会翻转图例以从顶部开始:

ggplot(faithfuld, aes(waiting, eruptions)) +
    geom_raster(aes(fill = density)) +
    scale_fill_continuous(trans = 'reverse')

您可以使用 RColorBrewer(link) 库中的调色板并指定颜色渐变的方向

library(RColorBrewer)
library(ggplot2)

ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = z, width = w), colour = "grey50") +
  scale_fill_distiller(palette ="RdBu", direction = -1) # or direction=1


# data
  df <- data.frame( x = rep(c(2, 5, 7, 9, 12), 2),
                    y = rep(c(1, 2), each = 5),
                    z = rep(1:5, each = 2),
                    w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2))