Farshid Ahrestani
Farshid Ahrestani

Reputation: 31

Stacking multiple columns on a geom_bar in ggplot2

Essentially:

  1. I want to draw a bar-graph that shows the aggregated value of two table columns, which I have managed to do using: err.bar <- ggplot(ss.data, aes(x=pop, y=obs+proc)) err.bar <- err.bar + geom_bar(position="stack", stat = "identity") err.bar

  2. I want to shade, not necessarily color, the two parts of the aggregated bars.

  3. Finally I want to color the bars by grouping them according to species (i.e., by species E & C as indicated on the x-axis labels on the Excel graph)

The data I am using is similar to:

Upvotes: 3

Views: 12507

Answers (1)

bdemarest
bdemarest

Reputation: 14667

Here is a solution that gets you most of what you want. But please note that ggplot is not designed to allow separate 'shade' and 'color' parameters in a single plot. Instead, I have shaded your obs and proc categories using grey fill colors, and I have grouped the species into facets (instead of coloring them differently).

library(ggplot2)
library(reshape2)

ss.data = data.frame(
    pop=c("E1", "E2", "E3", "E4", "E5", "E6", "E7", "C1", "C2", "C3", "C4"),
    obs=c(0.0027, 0.0018, 0.0464, 0.0095, 0.0034, 0.0117, 0.017, 0.1178,
          0.0449, 0.039, 0.0903),
    proc=c(0.0319, 0.0196, 0.0511, 0.0143, 0.0048, 0.0078, 0.0396, 0.1662,
           0.074, 0.1681, 0.1358), stringsAsFactors=FALSE)

# Add new column 'species' by removing the trailing digits from 'pop'.
ss.data$species = gsub("\\d", "", ss.data$pop)

# Convert data to long-form with 'melt' from the reshape2 package.
mdat = melt(ss.data, id.vars=c("pop", "species"),
            measure.vars=c("obs", "proc"))

plot_1 = ggplot(mdat, aes(x=pop, y=value, fill=variable)) +
         theme_bw() +
         geom_bar(position="stack", stat="identity") +
         scale_fill_manual(values=c("grey50", "grey80")) +
         facet_grid(. ~ species, space="free_x", scales="free_x",
             labeller=label_both)

ggsave("plot_1.png", plot=plot_1, width=6.5, height=4)

enter image description here

Upvotes: 10

Related Questions