Trent
Trent

Reputation: 55

Faceted bar charts from multiple columns in ggplot2

I have some data containing resistance data against three different antibiotics, each stored as a column.

Isolate MIC1    MIC2     MIC3
    1   0.008   0.064   0.064
    2   0.016   0.250   0.500
    3   0.064   0.125   32
...

I've plotted barcharts for each individual antibiotic thus:

ggplot(data, aes(factor(MIC1))) + geom_bar()

(the values are discrete as powers of 2 - 0.008, 0.016, 0.032 etc - plotting as factor evenly spaces the bars, if there more elegant way of doing this, please let me know!)

What I'd really like to do is to have a faceted stack of the three graphs with a shared x-axis.

Is there an easier way to do this than to recode the variables like this:

isolate  antibiotic  MIC
    1        1       0.008
    1        2       0.064
    1        3       0.064
    2        1       0.016
    2        2       0.250
    2        3       0.500
    3        1       0.064
    3        2       0.125
    3        3       32
...

and then doing it this way?

ggplot(data, aes(factor(MIC))) + geom_bar() + facet_grid(antibiotic ~ .)

Thanks in advance.

Upvotes: 1

Views: 3278

Answers (1)

Marius
Marius

Reputation: 60230

Reshaping your data frame to look like your second example is pretty easy using reshape2, to the point where I'm not sure it could really get much easier. Are there any specific problems you would have with this solution?

df = read.table(text="Isolate MIC1    MIC2     MIC3
    1   0.008   0.064   0.064
    2   0.016   0.250   0.500
    3   0.064   0.125   32", header=TRUE)

library(reshape2)
df_melted = melt(df, id.vars="Isolate", variable.name="antibiotic", value.name="MIC")
ggplot(df_melted, aes(factor(MIC))) + geom_bar() + facet_grid(antibiotic ~ .) 

Upvotes: 2

Related Questions