稳定的映射与ggplot2的scale_colour_discrete: drop不起作用?

3
如何在使用ggplot绘制不同图表时,使得drop=TRUE有效(因此图例仅包含子集中存在的类别),并尝试为不同图表中的类别提供稳定的颜色映射?这个问题与这个有关,特别是这个评论。下面是可复现的代码,摘自链接问题中的一个答案
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
                      x = rnorm(500, mean = rep(1:5, 100)),
                      y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))
ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point() + 
       scale_colour_discrete(drop=TRUE,limits = levels(dataset$fCategory))

为什么第二张图中的 drop=TRUE 不起作用? 图例仍然包含所有类别。 sessionInfo() 的输出结果为:
R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United     Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

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

other attached packages:
[1] ggplot2_1.0.0

loaded via a namespace (and not attached):
[1] colorspace_1.2-4 digest_0.6.8     grid_3.1.2       gtable_0.1.2         labeling_0.3    
[6] MASS_7.3-35      munsell_0.4.2    plyr_1.8.1       proto_0.3-10         Rcpp_0.11.3     
[11] reshape2_1.4.1   scales_0.2.4     stringr_0.6.2    tools_3.1.2     

我尝试了您的示例,并且在两个图中,类别A-E的颜色都很稳定(即相同)。无论是否使用drop=TRUE,效果都一样。这可能是与版本有关的问题吗? 我使用的是ggplot2_1.0.0。 - Marat Talipov
@MaratTalipov 稳定映射可以正常工作,但我的问题是关于 drop=TRUE 参数无法正常工作。第二个图例仍然包含所有类别。我已经编辑了我的问题以使其更清晰,并添加了会话信息。 - Sirvydas
1个回答

2

这可能是对 drop 的误解(不幸的是,帮助条目没有提供太多细节),也可能是一个错误。然而,我建议完全放弃使用 drop(顺便说一句),并设置 limitsbreaks 两个参数:

ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point() + 
  scale_colour_discrete(limits = levels(dataset$fCategory), 
                        breaks = unique(subdata$fCategory))

enter image description here

The colour set is consistent, the legend is fine.


谢谢您提出中断建议。我建议您编辑您的回答为 breaks = unique(subdata$fCategory),因为我们事先不知道有哪些级别存在。 - Sirvydas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接