[R] Color With a Function

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Fri Dec 20 03:44:19 CET 2013


Design questions ("why...") should go to the package maintainer.

You need to learn to ask complete questions [1] and post in plain text 
rather than HTML on this list.

I think that normal practice is to add a factor column that reflects the 
coloring you want, and then reference it. E.g.:

library(reshape2)
library(ggplot2)
set.seed(42)
df <- data.frame( matrix( rnorm(12*4,1,1), ncol=4 ) )
df$Month <- factor( 1:12 )
names( df ) <- c( paste0( "data", 1:4 ), "Month" )
dfm <- melt(df,measure.vars=c("data1", "data2", "data3", "data4" ) )
dfm$col <- "Nonnegative"
dfm$col[ dfm$value < 0 ] <- "Negative"
dfm$col <- as.factor( dfm$col )
ggplot(dfm, aes(x=Month,y=value,fill=col)) +
     geom_bar(stat = "identity",position="dodge") +
     facet_wrap(~variable,ncol=1, scales = "free_y") +
     scale_fill_manual( name="Sign", values=c( "red", "green" ) )

P.S.: Note that "df" is the name of a function provided in base R. In the 
long run you are better off using some other shorthand (I use "DF") 
variable name.

[1] 
http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example

On Thu, 19 Dec 2013, 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)
>
> Thanks,
> Bradford
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k



More information about the R-help mailing list