作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当使用 ggplot 并尝试对类别进行稳定的颜色映射时,如何使 drop=TRUE
在 scale_colour_discrete
中工作(因此图例仅包含子集中存在的类别)在不同的地 block ?
从 one of the answers 借用的可重现代码在链接的问题中:
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
最佳答案
这要么是对 drop
的作用的误解(不幸的是,帮助条目没有提供太多细节),要么是一个错误。但是,我建议完全放弃 drop
(双关语)并设置 limits
和 breaks
:
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point() +
scale_colour_discrete(limits = levels(dataset$fCategory),
breaks = unique(subdata$fCategory))
颜色设置一致,图例没问题。
关于r - 使用 ggplot2 scale_colour_discrete : drop does not work? 进行稳定映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28285728/
当使用 ggplot 并尝试对类别进行稳定的颜色映射时,如何使 drop=TRUE 在 scale_colour_discrete 中工作(因此图例仅包含子集中存在的类别)在不同的地 block ?
我是一名优秀的程序员,十分优秀!