How to set the color range of scale_colour_brewer() in ggplot2? (palette selected)

Yuyu ZENG picture Yuyu ZENG · Apr 6, 2015 · Viewed 10.6k times · Source

I am sorry I cannot offer an image because of limited reputation I have on this site...

I used the following code to generate my line chart in R:

p <- ggplot()+
geom_line(data=data, aes(x, y, color=Label))+ scale_colour_brewer(palette="Oranges")

I used the palette"Oranges" because I want to generate a series of lines with similar while different colors.

However, the color of lower/upper range is too light, so I want to set a limit for the palette to avoid whitish colors.

I know I should specify something like scale_color_gradient(low = "green", high = "red"), but how can I find the specify color with a given palette?

Many thanks!

Answer

bmayer picture bmayer · Nov 5, 2015

Since you have a discrete scale, you should be able to manually create the set of colors and use scale_color_manual without too much trouble.

library(ggplot2)
theme_set(theme_bw())
fake_data = data.frame(
    x = rnorm(42), 
    y = rnorm(42), 
    Label = rep(LETTERS[1:7], each = 6))

p_too_light <- ggplot()+ geom_line(data=fake_data, aes(x, y, color=Label))+ 
  scale_colour_brewer(palette="Oranges")
p_too_light

Now use brewer.pal and http://www.datavis.ca/sasmac/brewerpal.html.

library(RColorBrewer)
my_orange = brewer.pal(n = 9, "Oranges")[3:9] #there are 9, I exluded the two lighter hues

p_better <- ggplot()+ geom_line(data=fake_data, aes(x, y, color=Label))+ scale_colour_manual(values=my_orange)
p_better

If you have more than 6 categories, you could use colorRampPalette with the boundary colors from the brewer.pal call earlier. However, now choosing the palette scheme requires more thought (maybe why ggplot2 doesn't do this automatically for discrete scales).

fake_data2 = data.frame(
  x = rnorm(140), 
  y = rnorm(140), 
  Label = rep(LETTERS[1:20], each = 7))

orange_palette = colorRampPalette(c(my_orange[1], my_orange[4], my_orange[6]), space = "Lab")
my_orange2 = orange_palette(20)

p_20cat <- ggplot()+ geom_line(data=fake_data2, aes(x, y, color=Label))+
  scale_colour_manual(values=my_orange2)
p_20cat