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

I apologize, I can not offer an image due to the limited reputation on my site ...

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

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

I used the Oranges panel because I want to generate a series of lines with similar colors in different colors.

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

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

Thank you very much!

+6
source share
1 answer

Since you have a discrete scale, you should be able to manually create a set of colors and use scale_color_manual without any problems.

 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 can use colorRampPalette with border colors from the brewer.pal call earlier. However, now choosing a palette scheme requires more thought (perhaps why ggplot2 does not 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 
+4
source

Source: https://habr.com/ru/post/984726/


All Articles