nouse
nouse

Reputation: 3471

ggplot2: Stack barcharts with group means

I have tried several things to make ggplot plot barcharts with means derived from factors in a dataframe, but i wasnt successful. If you consider:

df <- as.data.frame(matrix(rnorm(60*2, mean=3,sd=1), 60, 2))
df$factor <- c(rep(factor(1:3), each=20))

I want to achieve a stacked, relative barchart like this: enter image description here

This chart was created with manually calculating group means in a separate dataframe, melting it and using geom_bar(stat="identity", position = "fill) and scale_y_continuous(labels = percent_format()). I havent found a way to use stat_summary with stacked barcharts.

In a second step, i would like to have errorbars attached to the breaks of each column. I have six treatments and three species, so errorbars should be OK.

Upvotes: 0

Views: 646

Answers (1)

heathobrien
heathobrien

Reputation: 1027

For anything this complicated, I think it's loads easier to pre-calculate the numbers, then plot them. This is easily done with dplyr/tidyr (even the error bars):

gather(df, 'cat', 'value', 1:2) %>% 
    group_by(factor, cat) %>% 
    summarise(mean=mean(value), se=sd(value)/sqrt(n())) %>% 
    group_by(cat) %>% 
    mutate(perc=mean/sum(mean), ymin=cumsum(perc) -se/sum(mean), ymax=cumsum(perc) + se/sum(mean)) %>% 
    ggplot(aes(x=cat, y=perc, fill=factor(factor))) +
        geom_bar(stat='identity') +
        geom_errorbar(aes(ymax=ymax, ymin=ymin))

enter image description here

Of course this looks a bit strange because there are error bars around 100% in the stacked bars. I think you'd be way better off ploting the actual data points, plus means and error bars and using faceting:

gather(df, 'cat', 'value', 1:2) %>% 
    group_by(cat, factor) %>% 
    summarise(mean=mean(value), se=sd(value)/sqrt(n())) %>% 
    ggplot(aes(x=cat, y=mean, colour=factor(factor))) +
        geom_point(aes(y=value), position=position_jitter(width=.3, height=0), data=gather(df, 'cat', 'value', 1:2) ) +
        geom_point(shape=5, size = 3) +
        geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.1) +
        facet_grid(factor ~ .)

enter image description here

This way anyone can examine the data and see for themselves that they are normally distributed

Upvotes: 2

Related Questions