r - ggplot : adding color aesthetic changes stack order

标签 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  

最佳答案

啊,这是一个答案 + 解决方法。发生这种情况是因为 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

关于r - ggplot : adding color aesthetic changes stack order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734285/

相关文章:

r - 从时间中提取小时的最快方法(HH :MM)

r - 使用流程图可视化 R 代码

r - R中不同级别的李克特分组

r - 如何在ggplot2的右侧放置转换的比例?

R 堆积条形图绘制 geom_text

r - 在 R 中将向量穷举成对的方法

mysql - 将 MySQL 数据库中的表读入 R

r - 在 R 中制作 WCS Munsell 颜色图表,scale_fill_manual,ggplot2 中的顺序问题

R/ggplot : Vertical strip text with facet_wrap

r - ggplot2 - 如何使用 data.frame 中的列标记 x-ticks?