Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot NA bar with ggplot2

Tags:

r

ggplot2

I want to plot a bar chart where the count of males, females and NAs is shown. The problem is that when I add the option fill=gender for colouring the bars I lose the NA bar. What option should I use to keep the NA bar also with colours?

name <- c("Paul","Clare","John","What","Are","Robert","Alice","Jake")
gender <- c("male","female","male",NA,NA,"male","female","male")

df <- data.frame(name,gender)

ggplot(subset(df, gender=="male" | gender=="female" | is.na(gender)), aes(x=gender, fill=gender)) +
  geom_bar() + 
  labs(x=NULL, y="Frequency") +
  scale_fill_manual(values=c("red", "blue", "black"))
like image 299
CptNemo Avatar asked Sep 23 '13 23:09

CptNemo


1 Answers

If you really have to have your NAs as they are, you can make gender into a factor that doesn't exclude NA:

# Convert to a factor, NOT excluding NA values
df$gender <- factor(df$gender, exclude = NULL)

ggplot(df, aes(x=gender, fill = gender)) +
  geom_bar(na.rm = FALSE) + 
  labs(x=NULL, y="Frequency") +
  scale_fill_manual("Gender", 
                    values=c("red", "blue", "black"))

enter image description here

NA still doesn't show up in the legend - ggplot doesn't expect to plot NAs here, which is why it's usually easier to recode them as I do in my other answer. Either way, I think you're going to have to modify your gender variable.

like image 100
Matt Parker Avatar answered Oct 16 '22 13:10

Matt Parker