naught101
naught101

Reputation: 19563

Plot mean and sd of dataset per x value using ggplot2

I have a dataset that looks a little like this:

a <- data.frame(x=rep(c(1,2,3,5,7,10,15,20), 5),
                y=rnorm(40, sd=2) + rep(c(4,3.5,3,2.5,2,1.5,1,0.5), 5))
ggplot(a, aes(x=x,y=y)) + geom_point() +geom_smooth()

graph output

I want the same output as that plot, but instead of smooth curve, I just want to take line segments between the mean/sd values for each set of x values. The graph should look similar to the above graph, but jagged, instead of curved.

I tried this, but it fails, even though the x values aren't unique:

ggplot(a, aes(x=x,y=y)) + geom_point() +stat_smooth(aes(group=x, y=y, x=x))
geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?

Upvotes: 8

Views: 18038

Answers (4)

dlaehnemann
dlaehnemann

Reputation: 701

Using ggplot2 0.9.3.1, the following did the trick for me:

ggplot(a, aes(x=x,y=y)) + geom_point() +
 stat_summary(fun.data = 'mean_sdl', mult = 1, geom = 'smooth')

The 'mean_sdl' is an implementation of the Hmisc package's function 'smean.sdl' and the mult-variable gives how many standard deviations (above and below the mean) are displayed.

For detailed info on the original function:

library('Hmisc')
?smean.sdl

Upvotes: 4

smillig
smillig

Reputation: 5351

You could try writing a summary function as suggested by Hadley Wickham on the website for ggplot2: http://had.co.nz/ggplot2/stat_summary.html. Applying his suggestion to your code:

p <- qplot(x, y, data=a)

stat_sum_df <- function(fun, geom="crossbar", ...) { 
 stat_summary(fun.data=fun, colour="blue", geom=geom, width=0.2, ...) 
} 

p + stat_sum_df("mean_cl_normal", geom = "smooth") 

This results in this graphic:

enter image description here

Upvotes: 3

Ramnath
Ramnath

Reputation: 55715

You can use one of the built-in summary functions mean_sdl. The code is shown below

ggplot(a, aes(x=x,y=y)) + 
 stat_summary(fun.y = 'mean', colour = 'blue', geom = 'line')
 stat_summary(fun.data = 'mean_sdl', geom = 'ribbon', alpha = 0.2)

Upvotes: 4

mnel
mnel

Reputation: 115435

?stat_summary is what you should look at.

Here is an example

# functions to calculate the upper and lower CI bounds
uci <- function(y,.alpha){mean(y) + qnorm(abs(.alpha)/2) * sd(y)}
lci <- function(y,.alpha){mean(y) - qnorm(abs(.alpha)/2) * sd(y)}
ggplot(a, aes(x=x,y=y))  + stat_summary(fun.y = mean, geom = 'line', colour = 'blue') + 
            stat_summary(fun.y = mean, geom = 'ribbon',fun.ymax = uci, fun.ymin = lci, .alpha = 0.05, alpha = 0.5)

enter image description here

Upvotes: 8

Related Questions