Reversing default scale gradient ggplot2

一曲冷凌霜 提交于 2021-02-07 05:20:44

问题


I am newbie, I am trying to desing a heat map. This is my code:

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 = "(%)")

Which produces a perfect chart, my problem is low levels are dark blue, and higher values are light blue, which is not intuitive. Most common way to do is use rev(). But in my case I dont know how to. So, is it possible to reverse this default scale? This is the legend

Other question, is there a way to create a scale gradient only with one colour. I mean, scale_fill_gradient/scale_fill_gradientn need to set a low color and high color (low = "", high = "") and I want to change the blue by red.

Thanks so much for your support.


回答1:


?scale_colour_gradient shows the default values of low = "#132B43" and high = "#56B1F7".

Simply switch those around:

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

Personally, I think this is less intuitive than the default.


Alternatively, you can use a reverse scale, but this will also flip the legend to start at the top:

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




回答2:


you can use the color palettes from RColorBrewer(link) library and assign the direction of the color gradient

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



来源:https://stackoverflow.com/questions/43515112/reversing-default-scale-gradient-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!