[R] plotting multiple variables in 1 bar graph

S Ellison S.Ellison at LGCGroup.com
Wed Oct 24 17:22:23 CEST 2012


> I'd greatly appreciate your help in making a bar graph with multiple
> variables plotted on it. All the help sites I've seen so far only plot 1
> variable on the y-axis
> ...
>
> I've spent several hours looking for code to do this but didn't find
> anything. I'd use the Excel graph except that it doesn't have the sd or se
> bars.
>
Perhaps something like lattice or ggplot would serve better?

Here's something using ggplot (which has prettier colours than lattice)


#Something like your data - with considerable licence on unreadable names!
abst <-structure(list(Count = c(17.03, 22.94, 28.38, 29.72, 28.37, 14.45, 
1.51, 0.54, 0.62, 1.52, 62.3, 70.6, 68.82, 64.75, 63.77, 3.17, 
2.78, 2.22, 2.03, 1.94, 0.61, 0.33, 0.74, 0.74, 0.58, 0.44, 0.12, 
0.37, 0.08, 0.41, 0.04, 0, 0.08, 0, 0.08, 1.96, 1.68, 2.84, 2.06, 
3.32, 0, 0, 0, 0, 0), Benthic = structure(c(2L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 4L, 
4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 8L, 8L, 
8L, 8L, 8L, 7L, 7L, 7L, 7L, 7L), .Label = c("Algae", "Coral", 
"Deadcoral", "Ind", "other", "softcoral", "something", "sponges", 
"xBiotic"), class = "factor"), Time = structure(c(1L, 2L, 3L, 
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("T 1", "T 2", 
"T 3", "T 4", "T 5"), class = "factor")), .Names = c("Count", 
"Benthic", "Time"), row.names = c(NA, -45L), class = "data.frame")

head(abst)

#Add an arbitrary 'std error'

abst$stderr <- 0.05*abst$Count

 library(ggplot2)
 b <- ggplot(subset(abst, Benthic!="something"), aes(x = Time, y = Count, fill=Time)) 
 bptot<-b + geom_bar(stat = "identity", position = "dodge")
 bptot + facet_grid(. ~ Benthic , scales="free_y", margins=T)
 
#or, for unequal scale heights - much easier to see individual trends
bwrap <- bptot + facet_wrap( ~ Benthic , scales="free", nrow=2)
bwrap

#Now add error bars
bwrap+geom_errorbar(aes(ymin=Count-stderr, ymax=Count+stderr), width=.3)

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}




More information about the R-help mailing list