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

2

17

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!

Ijssel answered 6/4, 2015 at 6:12 Comment(0)
S
14

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
Surprise answered 5/11, 2015 at 1:41 Comment(0)
P
2

A nice direct answer to this question is to use the {shades} library. For example, to reduce the lightness of scale_color_brewer by 20%, do:

library(shades)
lightness(scale_color_brewer(palette="Oranges"),
          scalefac(0.8))
Pratfall answered 19/3, 2022 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.