[R] ggplot2/aesthetic plotting advice

Ben Bolker bolker at ufl.edu
Thu Apr 23 06:19:51 CEST 2009


  Consider the following situation:

  we have quantified algal concentrations for
a variety of species using many samples at each
of three years.  It seems to make sense to generate
a line plot (matplot-like), with each species plotted
as a separate line, with the points connected to emphasize
the temporal pattern.

  The problem: lots of overlapping error bars.

  The question: from both a procedural and an aesthetic
point of view, what do people recommend?  Below is an
example that hacks (not quite "jitters", because it's
systematic) the x locations a bit, but I find it a bit
ugly.  (I was also hoping that ggplot had some magic
to do this automatically, but position_dodge doesn't
seem to work in this context ...)

  Ben Bolker

library(ggplot2)

nx <- 3
ngrp <- 5
nper <- 4
x <- rep(1:nx,ngrp*nper)
y <- runif(nx*ngrp*nper)
g <- factor(rep(1:ngrp,each=nx*nper))

dat <- data.frame(x,y,g)

se <- with(dat,tapply(y,list(g,x),sd)/table(g,x))
means <- with(dat,tapply(y,list(g,x),mean))
limits <- aes(ymax=means+se,ymin=means-se)
gg <- factor(rep(1:ngrp,nx))
xx <- rep(1:nx,each=ngrp)
p <- ggplot(dat,aes(y=c(means),x=xx,
                    group=gg,colour=gg))
p + geom_pointrange(aes(ymin=c(means-se),ymax=c(means+se)))
xdodge <- xx + rep(seq(-0.1,0.1,length=ngrp),nx)
p + geom_line() + geom_pointrange(aes(x=xdodge,
                                      ymin=c(means-se),
                                      ymax=c(means+se))) +
  scale_x_continuous(name="Year",breaks=1:3) +
  scale_y_continuous(name="Whatever")


-- 
Ben Bolker
Associate professor, Biology Dep't, Univ. of Florida
bolker at ufl.edu / www.zoology.ufl.edu/bolker
GPG key: www.zoology.ufl.edu/bolker/benbolker-publickey.asc




More information about the R-help mailing list