0
votes

I have set up factor levels to control the order in which stacked bars appear in ggplot's geom_col. Then I want to facet the bar plots by an additional factor. When I add "group" to the aes for geom_col, it loses the ordering of the bars.

This minimal example causes the problem, though I'm hoping I haven't left out any key complications in paring it down. I have deliberately ordered the levels of cyl in a non-intuitive ranking. In the first graph, the ranking is honored. In the faceted version it is not.

  library(ggplot2)
  m.cars <- mtcars
  m.cars$cyl <- factor(m.cars$cyl, levels = c(6, 8, 4))
  m.cars$carb <- factor(m.cars$carb)
  m.cars$vs <- factor(m.cars$vs, levels = c(1, 0)) 
  ggplot(data = m.cars) +
     geom_col(aes(x = gear, y = mpg, fill = cyl))

non-faceted version, with bar ordering respected

  ggplot(data = m.cars) +
     geom_col(aes(x = gear, y = mpg, fill = cyl, 
         group = vs)) +
     facet_wrap(~vs)

Faceted output with undesired ordered of elements within bars

I think the default ordering of a categorical variable when factor levels are not set is alphabetical. In my data, the values for the stack ordering variable, equivalent to cyl in the example, are characters already. It's not optimal but I tried altering my base data so that the order of stacking I want is alphabetical. As a parallel to the example, I changed gear from 4, 6, and 8 to "b4", "a6", and "c8". It made no difference.

This question has some similarity to Ordering of faceted stacked barplot with ggplot2 but the ordering they are struggling to control is that of the facets, while for me it's the order of the bar stacking.

I may have to resort to this idea from ggplot bar plot with facet-dependent order of categories but am hoping to use facets instead. "The only way to do this would be to make separate plots and use grid.arrange from the gridExtra package. But I agree that it generally doesn't result in a very nice plot." I have lots of legend complications, etc...

1

1 Answers

1
votes

Remove the group = ... from your code, and it should work as you expect.

ggplot(data = m.cars) +  
  geom_col(aes(x = gear, y = mpg, fill = cyl)) +
  facet_wrap(~vs)

Introducing a facet doesn't require adding a matching group as well. (You'll see group often used in geom_boxplot, and that may show you when and where to use those).