T. Beige T. Beige - 2 months ago 6
R Question

How to show missing values in legend of ggplot2?

I want to create a barplot with

ggplot2
. My problem is missing data which is plottet at least but missing in the legend.

For example, if M is my data:

aim = c(rep(1, 28), 0, rep(1,7))
type = c(rep(F, 10), rep(T, 4), rep(F, 4), NA, NA, rep(T, 5), rep(F, 12))
M = data.frame(aim, type)


Then, I can get a barplot like this:

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"))


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

Question: The legend ignores missing values. How can I avoid this problem?

Answer

May be you can try this:

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

Comments