0

I am trying to build a complex bar plot that has categories to distinguish. Here is the data frame

   Treatment      DCA.f Megalorchestia Talitridae Traskorchestia
1          A   (-Inf,0]       8.000000  4843.6667      1394.0000
2          U   (-Inf,0]      21.000000  2905.3333       483.6667
3          A    (0,0.1]      25.000000   254.8571        41.0000
4          U    (0,0.1]      30.714286   691.0000       360.1429
5          A  (0.1,0.2]      35.400000  1355.2000       127.4000
6          U  (0.1,0.2]     104.400000   705.4000        50.2000
7          A  (0.2,0.3]       3.857143   649.7143       633.4286
8          U  (0.2,0.3]      10.857143   510.4286       268.7143
9          A  (0.3,0.4]      13.444444   981.5556       207.5556
10         U  (0.3,0.4]      10.666667  1567.5556       417.5556
11         A (0.4, Inf]       0.000000     3.0000         1.2000
12         U (0.4, Inf]       0.000000     3.8000         0.0000

I want a barplot that for each DCA.f group shows 6 values for the three organisms categories (the right three columns), separated by treatment (A v U). So if you read the bottom of the plot there would be a big category for DCA.f and then with in that category there would be six bars. Two for each genera color coded by treatment. And then repeated for all DAC.f. I have looked through many of the other barplot posts and they have not gotten me anywhere.

Any help?

wraymond
  • 295
  • 1
  • 6
  • 17
  • Both `ggplot2` and `lattice` packages can do what you're looking for. Start simple and build up to the complex plot you're looking for. Often it might take re-shaping of your data (package `reshape2` and its function `melt`). – Justin Feb 18 '14 at 19:53
  • As @Justin suggested, try to `melt` your data. You will then have three predictor variables: 'Treatment', 'DCA.f' and 'variable'. You may have a look [**here**](http://stackoverflow.com/questions/20060949/ggplot2-multiple-sub-groups-of-a-bar-chart/20073020#20073020) where I tried to provide an answer for a similar setting (3 predictors). I am sure there are other nice(r) answer on SO! – Henrik Feb 18 '14 at 20:26

1 Answers1

0

Here is one possibility. When using barplot, each column of the input matrix will correspond to a group of bars, and each row to different bars within groups. Thus, we need to reshape the data so that columns represent the levels of 'DCA.f'

library(reshape2)
library(RColorBrewer)

# reshape data
df2 <- melt(df)
df3 <- dcast(df2, Treatment + variable ~ DCA.f)

# create color palette
ncols <- length(unique(df3$variable))
cols <- c(brewer.pal(ncols, "Greens"), brewer.pal(ncols, "Reds"))

# plot
barplot(as.matrix(df3[ , -c(1, 2)]),
        beside = TRUE,
        col = cols,
        cex.names = 0.7)

# add legend
legend(x = 15, y = 4000, legend = paste(df3$Treatment, df3$variable), fill = cols)

enter image description here

Henrik
  • 65,555
  • 14
  • 143
  • 159