r - How to make the error bars move with the barplot when re-ordering factors? -
i plotting barplot error bars. , here's got far. problem error bars not appear in place should be. if don't force id levels, removing df2id <- factor(df2$id, level = c('gary','jack', 'alice'))
line, looks fine.
id = c(rep('gary',10), rep('jack',10), rep('alice',10)) #gary has lowest mean , sd, alice has highest mean , sd var1 = c(rnorm(1:10)*1+10,rnorm(1:10)*10+20, rnorm(1:10)*100+30) df <-data.frame(id = id, var1 = var1) df2 <- ddply(df, 'id', summarise, mean = mean(var1), sd = sd(var1)) df2$id <- factor(df2$id, level = c('gary','jack', 'alice')) limits <- aes(ymax = df2$mean + df2$sd, ymin = df2$mean - df2$sd) ggplot(df2, aes(y=mean, x=id))+geom_bar(stat='identity')+ geom_errorbar(limits)+ facet_grid(.~id)
but need keep line can re-order sequence of panels. how can make error bars re-ordered too?
you should never use data.frame$column
ggplot, forces full vector on ggplot, bypassing data
argument can know groupings , such. in basic plots doesn't matter, if facet it's big problem.
so, solve problem, don't try specify limits
before plot. delete line , put same code (without df$
) in geom_errorbar
:
ggplot(df2, aes(y = mean, x = id))+ geom_bar(stat = 'identity')+ geom_errorbar(aes(ymax = mean + sd, ymin = mean - sd)) + facet_grid(. ~ id)
if using facets , don't want every id listed on each panel , on each x-axis, can set, x = "a"
in original aes()
.
Comments
Post a Comment