20

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.

Axeman
  • 32,068
  • 8
  • 81
  • 94
Tito Sanz
  • 1,280
  • 1
  • 16
  • 33
  • For your second question (please only ask one question at a time), you'll need two different shades of red. Like `'red'` and `scales::muted('red')`. You might want to look at the `viridis` package for superior color scales. – Axeman Apr 20 '17 at 09:17

2 Answers2

26

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

enter image description here

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

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
9

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

enter image description here

rafa.pereira
  • 13,251
  • 6
  • 71
  • 109