tags:

views:

294

answers:

3

Does anyone knows how to define a custom palette to be used in ggplot when geom="bar".

I have an array of colors I would like to use:

> rhg_cols
 [1] "#771C19" "#AA3929" "#E25033" "#F27314" "#F8A31B" "#E2C59F" "#B6C5CC"
 [8] "#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()
+1  A: 

First add, the colours to your data set:

mydata$col <- rhg_cols

Then map colour to that column and use scale_colour_identity

ggplot(mydata, aes(factor(phone_partner_products, colour = col))) + 
  geom_bar() + 
  scale_colour_identity()
hadley
mmm ... the first line has some problem... I have at least 800 row and the colors are only 10> mydata$col <- rhg_colsError in `$<-.data.frame`(`*tmp*`, "col", value = c("#771C19", "#AA3929", : replacement has 10 rows, data has 865
Libo Cannici
and of course the factor(phone_partner_products) returns only 5 elements, so a palette of 10 colors should be enough.
Libo Cannici
Oh, it's a palette. This is why reproducible code is always useful.
hadley
A: 

If the colours are a palette, use scale_colour_manual:

ggplot(mydata, aes(factor(phone_partner_products), colour = colour_variable)) +
  scale_colour_manual(colour = rhg_cols)
hadley
+1  A: 

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", hi = "#000000")

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

aL3xa