Is it possible to usa a custom-defined palette in ggplot2?

600 views Asked by At

I would like to use a custom defined palette in drawing a graph with ggplot2. I take just an example made with viridis:

library(ggplot2)
library(viridis)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_fill_viridis() + theme_bw()

My idea is to use the following palette:

palette <- c("#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B", 
              "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000")

library(scales)
show_col(palette)

enter image description here

I supposed to use scale_colour_manual(values = palette) but it looks like it doesn't take my custom-defined one. I am doing some kind of mistake?

library(ggplot2)
ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_colour_manual(values = palette) + theme_bw()

enter image description here

1

There are 1 answers

1
stefan On BEST ANSWER

The issue is that you are using scale_color_manual which will only work for discrete variables mapped on the color aes. As you have a continuous variable which is mapped on the fill aes one option would be to use scale_fill_gradientn:

set.seed(123)

library(ggplot2)

palette <- c(
  "#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B",
  "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000"
)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() +
  coord_fixed() +
  scale_fill_gradientn(colors = palette)