【问题标题】:Reversing default scale gradient ggplot2反转默认比例梯度ggplot2
【发布时间】:2017-04-20 09:11:06
【问题描述】:

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

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 = "") 并且我想将蓝色变为红色。

非常感谢您的支持。

【问题讨论】:

  • 第二个问题(请一次只问一个问题),您需要两种不同深浅的红色。喜欢'red'scales::muted('red')。您可能想查看 viridis 包以获得出色的色阶。

标签: r ggplot2 reverse heatmap


【解决方案1】:

?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')

【讨论】:

  • 非常感谢您以一种简单的方式改进了我的代码。这很完美!
【解决方案2】:

您可以使用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))

【讨论】:

  • 感谢您的回答!完美运行!
猜你喜欢
  • 2014-08-13
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多