0

How can I group bars in a barplot by a third variable?

enter image description here

I would like to achieve this in base R, without, for example, ggplot2, as in this related question. In another related question the groups of groups are labeled, but not (visually) grouped – as in my example above –, making the plot difficult to read.


Sample data:

groups = c("A", "B")
choices = c("orange", "apple", "beer")
supergroups = c("fruits", "non-fruits")
dat <- data.frame(
    group = rep(groups, c(93, 94)),
    choice = factor(c(
            rep(choices, c(51, 30, 12)),
            rep(choices, c(47, 29, 18))
        ),
        levels = choices
    ),
    supergroup = c(
        rep(supergroups, c(81, 12)),
        rep(supergroups, c(76, 18))
    )
)
barplot(table(dat), beside = TRUE)

Which returns the error:

Error in barplot.default(table(dat), beside = TRUE) : 
  'height' must be a vector or a matrix
  • 1
    Possible duplicate of [barplot x-axis labels with hierarchical grouping variables in separate rows](https://stackoverflow.com/questions/18776078/barplot-x-axis-labels-with-hierarchical-grouping-variables-in-separate-rows) – Henrik Aug 18 '17 at 08:46
  • @user8183921 I doubt that it is the _only_ way to do it. You might consider edit your question, and describe (with a simple sketch?) in which way the linked Q&A doesn't give you the desired result. A side note: It is slightly annoying that `barplot` doesn't have an `at` argument, like `boxplot` has, i.e. "numeric vector giving the locations where the boxplots should be drawn". Cheers. – Henrik Aug 18 '17 at 09:03
  • ggplot solution: `ggplot(dat, aes(choice, fill=group)) + geom_bar(width=.5) + facet_grid(~supergroup, scales="free_x", space="free")` – Adam Quek Aug 18 '17 at 09:08
  • Thank you, @Henrik, I added a brief explanation as to how the answer to that possible duplicate question does not answer my question. I visual example of what I want to achieve is already part of my question. –  Aug 18 '17 at 09:09
  • Thank you, @AdamQuek. I don't have ggplot2 installed, so I cannot quickly test your code and look at the result, but the reason that I want to avoid ggplot2 is that plots made with that library look so different from the other plots in my papers which I created using base R, that I have to spend endless time fiddling with the settings for ggplot2 to achieve a base R look. Also, the overwhelmingly many options in ggplot2 feel too much like using Word to me ... ;-) –  Aug 18 '17 at 09:17

0 Answers0