arvi1000
arvi1000

Reputation: 9582

ggplot: adding color aesthetic changes stack order

Found a weird edge case.

Let's say you want a stacked bar plot, with labeled segments (leaving aside whether this kind of plot is optimal data viz)

library(ggplot2)
set.seed(123)
dat <- data.frame(x = rep(1:5, each=3),
                  y = round(runif(5*3, 5, 10)),
                  category = letters[1:3])

# this looks normal: labels on correct segments
ggplot(dat,
       aes(x, y, fill=category, label=paste0(category, ': ', y))) +
  geom_col() +
  geom_text(position = position_stack(vjust=.5))

enter image description here

Now let's recolor just some of the labels:

# this is weird now
ggplot(dat,
       aes(x, y, fill=category, label=paste0(category, ': ', y))) +
  geom_col() +
  geom_text(aes(color = category == 'a'),
            position = position_stack(vjust=.5)) +
  scale_color_manual(values = c("black", 'white'))

enter image description here

The stack order has been changed, which is unexpected, and I'm not sure how one would fix this.

> sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.0.0.9000

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.16     digest_0.6.15    withr_2.1.2      dplyr_0.7.4      assertthat_0.2.0 grid_3.5.0       plyr_1.8.4       R6_2.2.2        
 [9] gtable_0.2.0     magrittr_1.5     scales_0.5.0     pillar_1.2.2     rlang_0.2.1      lazyeval_0.2.1   bindrcpp_0.2.2   labeling_0.3    
[17] tools_3.5.0      glue_1.2.0       munsell_0.4.3    yaml_2.1.19      compiler_3.5.0   pkgconfig_2.0.1  colorspace_1.3-2 bindr_0.1.1     
[25] tibble_1.4.2  

Upvotes: 3

Views: 278

Answers (1)

arvi1000
arvi1000

Reputation: 9582

Ah, well here's an answer + work-around. This happens because the aes(color = ...) call is invoked at the geom_text level, rather than in the initial ggplot call.

Unifying to a single aes call will cause geom_col and geom_text to respect the same order, but requires a little hack to get the color aesthetic to show up only for the text layer:

ggplot(dat,
       aes(x, y, fill=category, label=paste0(category, ': ', y),
           color = category == 'a')) +

  # if you call geom_col just like this, you'll get colored borders
  # geom_col() +

  # so you have to blank out the color aesthetic for this geom
  geom_col(color=NA) +

  geom_text(position = position_stack(vjust=.5)) +

  scale_color_manual(values = c("black", 'white'))

enter image description here

Upvotes: 3

Related Questions