Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a pre-defined color palette in ggplot

Tags:

r

ggplot2

Does anyone know how to use a pre-defined color palette in ggplot?

I have a vector of colors I would like to use:

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

But when I try to pass it to nothing happened

ggplot(mydata, aes(factor(phone_partner_products)), color = rhg_cols) +   geom_bar() 
like image 429
Liborio Francesco Cannici Avatar asked Jun 20 '10 12:06

Liborio Francesco Cannici


People also ask

How do you set a color palette in R?

In R, it is possible to specify a color in several ways: by name, col = "red" ; by hex code, col = "#FF0000" ; or by number, col = 2 . The last of these, a numeric color specification, is a numeric index into a “color palette”, which is controlled via the palette() function.

What is the default color palette in Ggplot?

By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars.

Which R package can we use to add compelling color schemes to our visualizations?

The R package ggsci contains a collection of high-quality color palettes inspired by colors used in scientific journals, data visualization libraries, and more.


2 Answers

You must put colour = rhg_cols inside aes(). As far as I can tell, you want to apply gradient to bars (in barplot) with factor variable on the abscissa? Then use fill - try this instead:

ggplot(mydata, aes(factor(phone_partner_products), fill = factor(phone_partner_products))) +   geom_bar() +    scale_fill_manual(values = rhg_cols) 

or try to achieve approximate replica with:

ggplot(mydata, aes(factor(phone_partner_products), fill = phone_partner_products))) +   geom_bar() +    scale_fill_gradient(low = "#771C19", high = "#000000") 

Notice that in second case a continuous variable is passed to fill aesthetics, therefore scale_fill_gradient is passed afterwards. If you pass a factor to the fill aes, you must stick with scale_fill_manual(values = rhg_cols).

like image 106
aL3xa Avatar answered Sep 18 '22 16:09

aL3xa


If the colours are a palette, use scale_colour_manual:

ggplot(mydata, aes(factor(phone_partner_products), colour = colour_variable)) +   scale_colour_manual(values = rhg_cols) 
like image 38
hadley Avatar answered Sep 17 '22 16:09

hadley