stacked bar graph order and label positioning

53 views
Skip to first unread message

RESC

unread,
Apr 7, 2017, 6:00:53 PM4/7/17
to ggplot2
Dear ggplotters,

I'm new to R and ggplot, and I'm having some trouble running code that has previously worked, but not today.

The code below replicates my issue. When creating a stacked bar graph previously, the first factor would be put at the bottom of the stack. To create labels that were positioned correctly, you could arrange appropriately, and calculate a cumulative sum for the label position.
However, it now appears that the first factor is on top of the stack, which messes with the label positioning. I've run the examples from the R Graphics Cookbook and I'm noticing the same thing. I've uninstalled and re-installed ggplot to with no change.

Is this a new feature, so that the stack order matches the legend order? Do I need to change all my scripts to re-calculate the label positions based on the reverse order?


library(plyr)
library(ggplot)

df <- data.frame(x = c("a", "b"), fill = c("x","x","y","y"), y = c(1,2,3,4))

arr <- arrange(df, x, fill)
arr <- ddply(arr, "x", transform, label_y = cumsum(y))

ggplot(arr, aes(x = x, y = y, fill = fill)) +
  geom_bar(stat = "identity")+
  geom_text(aes(y=label_y, label=y), vjust = 1.5, colour = "white")

Thanks for any feedback!

Wouter van der Bijl

unread,
Apr 10, 2017, 5:19:49 AM4/10/17
to ggplot2
You are correct, the default ordering has changed.

You can either:
- calculate your labels differently (e.g. cumsum(rev(y)) )
- change the positioning to the old default by doing:

ggplot(arr, aes(x = x, y = y, fill = fill)) +

  geom_bar
(stat = "identity", position = position_stack(reverse = TRUE)) +

  geom_text
(aes(y=label_y, label=y), vjust = 1.5, colour = "white")

HTH,
W.

Joyce Robbins

unread,
Apr 10, 2017, 11:20:52 AM4/10/17
to Wouter van der Bijl, ggplot2
To take this in a different direction: the need/desire to label the bars in a stacked bar chart is due to the fact that they are hard to read since with the exception of the bottommost bars, the bars that you'd want to compare don't start at the same vertical location. Grouped bar charts or facetting would avoid the need to label.

Joyce

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+unsubscribe@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages