Skip to content
Prev 261846 / 398503 Next

Y error bars, dates on the X-axis

Hi:

Here's one way to do it with ggplot2; it contains the basic elements
you need, including a 'geom' for error bars. Two data frames are used:
one that contains the raw data, another that produces the daily means
and standard deviations. A couple of bells and whistles are added
(e.g., point jittering and a line to connect the daily means), but
don't let it intimidate you if this is all new.

library(ggplot2)      # also loads the plyr package to be used below

# Generate the data:
df <- data.frame(Date = rep(seq(as.Date('2011-05-01'), by = 'days',
length = 10), each = 50),
                 y = rnorm(500), stringsAsFactors = FALSE)

# Summarize it, outputting the mean and standard deviation by Date:
dfsumm <- ddply(df, .(Date), summarise, yavg = mean(y), sdy = sd(y))

# This plot uses two data frames. Each 'geom' is a type of graphical object
# which adds a 'layer' to the plot. The first is a scatterplot of the data where
# x = Date, y = y and the points are jittered. aes() represents the 'aesthetics'
# of the geom, which in this case are the x and y variables of the scatterplot.
# The second layer is the error bar plot, which needs x, ymin and ymax as
# aesthetics; width refers to the width of the horizontal bars, size
to its thickness.
# Point and line plots complete the display. Notice that after the first layer,
# the input data frame is dfsumm rather than df. The common date in each
# data frame is key.

ggplot() +
   geom_point(data = df, aes(x = Date, y = y),
              position = position_jitter(width = 0.2)) +
   geom_errorbar(data = dfsumm, aes(x = Date, ymin = yavg - sdy,
                 ymax = yavg + sdy), colour = 'red', width = 0.4, size = 1.5) +
   geom_point(data = dfsumm, aes(x = Date, y = yavg), colour = 'blue',
size = 2.5) +
   geom_line(data = dfsumm, aes(x = Date, y = yavg), colour = 'blue', size = 1)

If you find this interesting, see http://had.co.nz/ggplot2 for more
information about the package, including a set of on-line help pages.

HTH,
Dennis
On Fri, Jun 3, 2011 at 8:41 AM, Terhukka <terhi at live.co.uk> wrote: