0

I'm making a rather complicated bar chart, where I've added an additional pareto line. Usually my bar chart works fine - also with the geom_text() labels on top of the stacked bars. But now I can't seem to make it work. The geom_text() for the geom_bar() goes in the wrong order (top to buttom) on every bar, and I have no idea why. This is (some of) my code:

ggplot() +
  theme_mso() +
  geom_bar(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor), stat = "identity") +
  geom_text(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, label = n), position = position_stack(vjust = .5)) +
  scale_fill_manual(values = col) +
  geom_point(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret)) +
  geom_line(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, group = 1), stat = "identity") +
  scale_y_continuous(sec.axis = sec_axis(~(./total_value)*100, name = "Procent")) +
  geom_text(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, label = procent), position = position_stack(vjust= 1.08)) +

.... and so on. Hope it makes sense and that somebody can help!

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 2
    To help us to help would you mind providing [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data to test your code. – stefan Aug 25 '21 at 14:59
  • ... but you could try with adding the group aes, i.e. `group = alvor`, to geom_text. – stefan Aug 25 '21 at 15:00
  • group = alvor worked!!! Don't know why I didn't try that myself... Thank you so much stefan! – Sejersboll Sep 01 '21 at 08:10

2 Answers2

0

You can try specifying the level order of your groups to the order that you like. For each geom that has a specified fill, add in the level order specification.

#Specify level orders
level_order <- c("A", "B", "C", "D", "E", "F")

Modify your ggplot code to add the level order to the appropriate aesthetics.

geom_bar(aes(x=X, y=Y, fill=factor(group, level_order))
aboyd
  • 3
  • 3
0

Just to highlight: (as missed it on the first pass, and lukers can't comment) - Stefan's suggestion above of passing the variable to fill and to group is the "perfect" answer to this:

    geom_label( ..., aes( ..., fill = alvor, group = alvor )) +

I too was making an overly-complicated barchart and came up against this seemingly intractable issue. Presumably it restricts the labelling to be placed within the appropriate cell - in any case, it allows lunch to happen.