【发布时间】:2017-09-12 09:32:35
【问题描述】:
我正在做一个更大的项目,为此我在 ggplot2 中创建了几个图。这些图涉及在几个不同的谨慎类别(想想:国家、物种、类型)中绘制几个不同的结果。我想完全修复离散类型到颜色的映射,以便 Type=A 始终显示为红色,Type=B 始终显示为蓝色,等等,无论存在哪些其他因素。我知道scale_fill_manual(),我可以在其中手动提供颜色值,然后使用drop = FALSE,这有助于处理未使用的因子水平。但是,我发现这非常麻烦,因为每个绘图都需要一些手动工作来处理以正确的方式对因子进行排序、对颜色值进行排序以匹配因子排序、删除未使用的级别等。
我正在寻找一种方法,我可以将一次全局因子级别映射到特定颜色(A=绿色、B=蓝色、C=红色、...),然后只需去绘制我喜欢的任何东西,然后 ggplot 选择正确的颜色。
这里有一些代码来说明这一点。
# Full set with 4 categories
df1 <- data.frame(Value = c(40, 20, 10, 60),
Type = c("A", "B", "C", "D"))
ggplot(df1, aes(x = Type, y = Value, fill = Type)) + geom_bar(stat = "identity")
# Colors change complete because only 3 factor levels are present
df2 <- data.frame(Value = c(40, 20, 60),
Type = c("A", "B", "D"))
ggplot(df2, aes(x = Type, y = Value, fill = Type)) + geom_bar(stat = "identity")
# Colors change because factor is sorted differently
df3 <- data.frame(Value = c(40, 20, 10, 60),
Type = c("A", "B", "C", "D"))
df3$Type <- factor(df3$Type, levels = c("D", "C", "B", "A"), ordered = TRUE)
ggplot(df3, aes(x = Type, y = Value, fill = Type)) + geom_bar(stat = "identity")
【问题讨论】: