1

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.

Brett
  • 13
  • 3
  • I'm really curious to understand what idea underlies your visualisation? – tjebo Feb 15 '23 at 08:06
  • 1
    The original data relates to alcohol consumption, with the x-axis representing weeks, and the y-axis representing standard drinks. The two factors are *max* standard drinks in a given week (as in, on any single day), and *total* standard drinks in a given week. So, in short, one of the two values will always be equal to or less than the other, and I want that value (the lesser one) to be 'fronted' so you can see both in a single bar. Hope that makes sense! – Brett Feb 15 '23 at 19:46
  • That makes sense! Also kind of nice to represent drink level with "fill of something max". Thanks for taking the time to answer ! – tjebo Feb 15 '23 at 20:14

1 Answers1

3

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")

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Agh, I knew I'd kick myself when I found out what the answer was! Thank you very much, this is perfect :-) – Brett Feb 15 '23 at 19:47