3

How do I use ggplot2 with stat_summary to show colours of my choice? Eg.:

simVol  <- data.frame(simId=c(1,1,1,1,2,2,2,2), 
                      farm=rep(c('farm A', 'farm A', 'farm B', 'farm B'),2),
                      period=rep(1:2,4), 
                      volume=c(9,21,12,18,10,22,11,19))

P10meanP90 <- function(x) data.frame(
  y = mean(x), 
  ymin = quantile(x, .1),
  ymax = quantile(x, .9)
)

This command plots the distribution of volume at each farm against the period, using default colours:

ggplot(simVol, aes(x=period, y=volume, colour=farm)) + 
    stat_summary(fun.data="P10meanP90", geom="smooth", size=2)

However, if I add colour='green' to the arguments of stat_summary, it plots instead the aggregate across farms. I've tried using colour=c('green','orange'), but this still only shows a green line.

How do I change the colours in this plot?

thanks

Racing Tadpole
  • 4,270
  • 6
  • 37
  • 56

1 Answers1

5

scale_colour_manual is the function you're looking for. http://docs.ggplot2.org/0.9.3.1/scale_manual.html

ggplot(simVol, aes(x=period, y=volume, colour=farm)) +
    stat_summary(fun.data="P10meanP90", geom="smooth", size=2) +
    scale_colour_manual(values = c("green", "orange"))

enter image description here

Jake Burkhead
  • 6,435
  • 2
  • 21
  • 32
  • Perfect - thanks! In fact I'm also using the `fill` argument to provide a colour for the P10-P90 range. Is there a way to provide different values for that for each farm too? thanks! – Racing Tadpole Feb 16 '14 at 23:00
  • @RacingTadpole I added a link to the docs for `scale_colour_manual` and the other functions which control scales for different aesthetics. Look at `scale_fill_manual` – Jake Burkhead Feb 16 '14 at 23:06
  • 1
    Thanks. I just tried `ggplot(simVol, aes(x=period, y=volume, colour=farm)) + stat_summary(fun.data="P10meanP90", geom="smooth", size=2) + scale_colour_manual(values = c("green", "orange")) + scale_fill_manual(values = c("cyan", "pink"))` and the fill is still grey - am I using it wrong? – Racing Tadpole Feb 16 '14 at 23:21
  • 3
    You have to map a variable to the `fill` aesthetic. Change the first part to `ggplot(simVol, aes(x = period, y = volume, colour = farm, fill = farm))` – Jake Burkhead Feb 16 '14 at 23:29