如何在ggplot2的图例中显示缺失值?

时间:2016-09-20 07:48:01

标签: r ggplot2

我想用 g <- ggplot(M, aes(as.character(aim))) g + geom_bar(aes(fill=as.character(type)), position= "dodge") + scale_fill_discrete(name="Type", breaks=c("TRUE", "FALSE", "NA"), labels=c("existing", "not existing", "missing values")) + scale_x_discrete(labels = c("bad", "good")) 创建一个条形图。我的问题是缺少数据,这至少在图例中是缺少的。但

例如,如果M是我的数据:

{{1}}

然后,我可以得到一个像这样的条形图:

{{1}}

Result of this code leads into a graphic without an explanation for the grey bar chart.

问题:图例会忽略缺失的值。我该如何避免这个问题?

1 个答案:

答案 0 :(得分:0)

可能你可以试试这个:

aim = c(rep(1, 28), 0, 0, rep(1,7))
type = c(rep(F, 10), rep(TRUE, 4), rep(F, 4), NA, NA, rep(TRUE, 5), rep(F, 12))
M = data.frame(aim, type)
M[is.na(M$type),] <- 'NA'
g <- ggplot(M, aes(as.character(aim)))
g + geom_bar(aes(fill=as.character(type)), position= "dodge")  + 
    scale_fill_discrete(name="Type", breaks=c("TRUE", "FALSE", "NA"),    
    labels=c("existing", "not existing", "missing values")) + 
    scale_x_discrete(labels = c("bad", "good"))

enter image description here