Search code examples
rggplot2position-dodge

Overlaying two bars in ggplot2 using position_dodge() without changing alpha value


What I'm wanting to do is have non-additive, 'stacked' bars, which I understand is achieved using position_dodge, rather than "stack". However, this does not behave as I expected it to.

The closest answer to what I'm after is here, but the code on that post causes exactly the same problem I'm running into.

A very basic example:

library(ggplot2)
example <- data.frame(week_num = c(1, 1),
                      variable = c("x", "y"),
                      value = c(5, 10))
ex <- ggplot(example, aes(x = week_num, y = value, fill = variable))
ex <- ex +
  geom_bar(stat = "identity", position = position_dodge(0))
print(ex)

What you get is essentially a single blue bar, representing the variable 'y' value of 10, with no sign of the 'x' value of 5:

Chart with lower value hidden

So far, the only way around this I've found is to make the width argument of position_dodge, say, 0.1, to get something like this, but that's not ideal.

Chart with lower value visible

Essentially, I want to 'front' the lower of the two values, so in this case what I'd want is a bar of height 10 (representing variable = , but with the lower half (up to 5) filled in a different colour.


Solution

  • One option to fix your issue would be to reorder your data. Observations are plotted in the order as they appear in your dataset. Hence, reorder you dataset so that lower values are at the end and will plotted last. Moreover, you could use position="identity" and geom_col (which is the same as geom_bar(stat="identity")):

    library(ggplot2)
    
    example <- dplyr::arrange(example, week_num, desc(value))
    
    ggplot(example, aes(x = week_num, y = value, fill = variable)) +
      geom_col(position = "identity")