Add mean value line of groups with geom_line()

27,571 views
Skip to first unread message

Idris Raja

unread,
Sep 27, 2011, 1:13:58 PM9/27/11
to ggplot2

# I am trying to add a line to each facet of a plot that shows the average of
# all points at each x value (see the attached plot).

# Essentially I've drawn what I want in green to each facet of the plot. The green
# line is the average of all points at that x value (well it's supposed to be, I
# certainly didn't draw it that well.) 

# How can I add a line that is an average of each point at x, for each facet?
# Thanks

# Sample Data
x <- seq(1:25)
y <- rnorm(mean = 0, sd = 10, 100)

a <- rep('a', 25)
b <- rep('b', 25)
c1 <- rep('c', 25)
d <- rep('d', 25)
type <- c(a, b, c1, d)
bucket = c(rep('hi', 50), rep('lo', 50))
df <- data.frame(x, y, type, bucket)

# Plot Example, see attachment
p <- ggplot(df, aes(x, y, group = type))
p <- p + geom_point() + geom_path(aes(colour = type)) + facet_grid(bucket~., 
       scales = 'free_y')
p

facet.jpeg

Brian Diggs

unread,
Sep 27, 2011, 1:41:26 PM9/27/11
to ggplot2

p + stat_summary(aes(group=bucket), fun.y=mean, geom="line", colour="green")

You need to set the group to the faceting variable explicitly since
otherwise it will be type and bucket (which looks like type since type
is nested in bucket).

--
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University

Reply all
Reply to author
Forward
0 new messages