[R] Color With a Function

Jim Lemon jim at bitwrit.com.au
Fri Dec 20 05:57:29 CET 2013


On 12/20/2013 10:38 AM, bradford wrote:
> I use ggplot2 a lot and am wondering why I can't just color with a
> function?  For example, if value<  0 then use red else use green.
>
> How would you guys suggest to color these bar graphs so that positive is
> green and negative is red?
>
> ggplot(melt(df,measure.vars=c("data1", "data2", "data3", "data4")),
> aes(x=Month,y=value)) + geom_bar(stat = "identity") + facet_wrap(~variable,
> ncol=1, scales = "free_y") + scale_y_continuous(labels=comma)
>
Hi Bradford,
If you are using numerically designated colors it is fairly easy. Using 
your example above:

col<-(value >= 0) + 2

As "red" is equivalent to "2" and "green" to "3" in the default palette, 
col will be a vector of 2s and 3s depending upon the sign of "value. 
This can be passed to whatever color argument you are using.

Jim



More information about the R-help mailing list