2016-03-03 126 views
0

是否有任何自動的方式來保持ggplot2使用它不同的顏色,如果一個特定的類是否存在或不在給定的情節?ggplot2 - 保持空類的顏色

對於以下問題:

library(ggplot2) 

set.seed(100) 

data <- data.frame(y=rnorm(100,2),class=sample(c("A","B","C"),100,rep=T), 
        stringsAsFactors=T) 

output <- ggplot(data[which(data[,"class"] != "B"),], 
       aes_string(x="class", y="y", fill="class")) + 
    geom_boxplot() + 
    scale_x_discrete(limits=c("A","B","C"), "class", drop=F) 

如果我不使用B類的樣品,我得到了以下情節: Boxplot without Class B

output <- ggplot(data, 
       aes_string(x="class", y="y", fill="class")) + 
    geom_boxplot() + 
    scale_x_discrete(limits=c("A","B","C"), "class", drop=F) 

但我想如果所有類都存在,請保留調色板: Boxplot with all the Classes

我知道我可以手動調色板,但我想知道它,我可以強制ggplot考慮所有的類,即使其中一個不存在。

回答

1

你已經知道如何做到這一點:

ggplot(data[which(data[,"class"] != "B"),], 
       aes_string(x="class", y="y", fill="class")) + 
    geom_boxplot() + 
    scale_x_discrete(limits=c("A","B","C"), "class", drop=F) + 
    scale_fill_discrete(drop = F) 

resulting plot