Skip to content
Prev 127317 / 398500 Next

Help: Side-by-side named barplot bars

On 10/18/07, Jim Lemon <jim at bitwrit.com.au> wrote:
I'm a strong believer in always storing data in data.frames, so the
first thing I'd do with your data is put it in that form.  This also
has the nice side effect of making the data self-documenting.  I'd
process Jim's example data as follows:

library(reshape)

df1 <- melt(mat1)
df2 <- melt(mat2)

names(df1) <- names(df2) <- c("species", "variable", "value")
df1$expt <- "one"
df2$expt <- "two"

df <- rbind(df1, df2)

It's then easy to plot the data with lattice or ggplot2.  The examples
below use ggplot2.

library(ggplot2)

qplot(variable, value, data=df, geom="bar", stat="identity",
fill=expt, position="dodge", facets = . ~ species)

Another option would be to use a dot plot instead - this has a much
higher data-ink ratio, and is arguably more correct when the values
don't represent sums.

qplot(variable, value, data=df, colour=expt, facets = . ~ species)

You could also connect the two experiments with a line:

qplot(variable, value, data=df, colour=expt, facets = . ~ species) +
geom_line(aes(group=variable), colour="grey")

If you really want the labels (and I wouldn't recommend it - it's a
graph not a table), you can add the following line to either of the
above calls:

+ geom_text(aes(label = formatC(value, digits=2), vjust = 0))

If you want the axes flipped (so it's easier to read the text labels), add:

+ coord_flip()

Regards,

Hadley