ggplot:添加颜色美学更改堆栈顺序

时间:2018-08-07 19:39:47

标签: r ggplot2

发现了一个奇怪的边缘情况。

比方说,您想要一个带有标记段的堆积条形图(不考虑这种图是否是最佳数据)

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

现在让我们仅对一些标签重新着色:

# 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

堆栈顺序已更改,这是出乎意料的,我不确定该如何解决。

> 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  

1 个答案:

答案 0 :(得分:2)

嗯,这是一个答案+解决方法。发生这种情况是因为aes(color = ...)调用是在geom_text级别而不是在初始ggplot调用中进行的。

统一为一个aes调用将导致geom_col和geom_text遵循相同的顺序,但是需要一点技巧才能使颜色美观仅显示在文本层上:

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