tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.45k stars 2.02k forks source link

Setting 'fill' for data label on stacked geom_bar inverts order of labels #2198

Closed ghost closed 7 years ago

ghost commented 7 years ago

First: Hadley, you are truly amazing. To me, you are the personification of data science. I'm a PhD student (antimicrobial resistance analysis, really cool) and I'm always citating your packages that I use in papers (mostly ggplot2, dplyr and readr). Thanks for making the life of this microbiologist so much easier!

Now the bug: When using fill on a label in conjunction with a stacked plot, the order of labels get inverted.

# create a nice table
tbl2 <-
structure(list(x = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 
3L, 4L, 5L, 6L), .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), 
    y2 = c("type 1", "type 1", "type 1", "type 1", "type 1", 
    "type 1", "type 2", "type 2", "type 2", "type 2", "type 2", 
    "type 2"), y = c(210, 131, 149, 215, 325, 203, 239, 103, 
    172, 195, 189, 157)), .Names = c("x", "y2", "y"), row.names = c(NA, 
-12L), class = "data.frame")

# create a nice stacked plot
p <- ggplot(data = tbl2, 
            aes(x = x, 
                y = y, 
                fill = y2)) + 
  geom_bar(width = 0.65,
           stat = 'identity',
           position = 'stack')

# Win 10 x64
# R version 3.4.0 (2017-04-21)
# RStudion version 1.0.143, desktop
# ggplot2 version 2.2.1

Now watch 😉

This code:

p + geom_label(aes(label = y),
               position = position_stack(vjust = 0.5),
               size = 2.75,
               colour = 'white')

Gives the expected result (although the coloured legend boxes contain a small white a) : image

Whereas this code:

p + geom_label(aes(label = y),
               position = position_stack(vjust = 0.5),
               size = 2.75,
               colour = 'white',
               # only difference: add fill
               fill = 'black')

Inverts the order, and plots the labels on the other bar: image

The alignment is also inverted, as you can see.

ghost commented 7 years ago

although the coloured legend boxes contain a small white a

Should I file this as a different issue?

hadley commented 7 years ago

That's because you're overriding the fill aesthetic which is used to define the grouping, which affects the ordering. I think if you set group = y2 you should be ok.