rggplot2plotstacked-chartstacked-bar-chart

How to make a Non-Cumulative stacked bar chart in ggplot


If I have a data like this:

df <- tibble::tribble(
  ~x, ~yvalue, ~variable,
  "a", 1,  "red",
  "a", 2,  "blue",
  "b", 1,  "red",
  "b", 3,  "blue",
  "b", 0, "blue"
)

I want to make a chart like a stacked bar chart of values (not counts), but instead of the bars stacking cumulatively, I basically want, for each value of x ie a or b, a single bar showing for that value, which is made up of overlapping bars of different colors, one for each variable type red/blue. When I use:

ggplot(data = df, aes(x, y, group = variable)) +
  geom_col(aes(fill = variable))

I get a stacked count. So for eg, the first bar, where x = 'a', has a 1 unit high bar(red), then another 2 unit high bar on top (blue) bringing it up to 3. What I want is for this to show a 1 unit high bar(red), then another 1 unit high bar on top (blue) bringing the total height for to 2 for the blue bar.

Any help would be appreciated. I can't show you my expected output because unfortunately I can't get it to work!


Solution

  • The individual bars of a geom_col will be drawn in the order in which they appear in your data frame. You therefore need to arrange your data frame in descending order of yvalue and use position = 'identity' to get a non-stacking bar plot where all the bars are visible (unless you have two of the same height, in which case one will be invisible by definition)

    ggplot(data = df[order(-df$yvalue),], aes(x, yvalue)) +
      geom_col(aes(fill = variable), position = 'identity') +
      scale_fill_identity()
    

    enter image description here