如何使用ggplot2绘制NA栏

Cpt*_*emo 8 r ggplot2

我想绘制一个条形图,其中显示了男性,女性和NA的数量.问题是,当我添加fill=gender用于着色条的选项时,我失去了NA条.我应该使用什么选项来保持NA栏的颜色?

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"))
Run Code Online (Sandbox Code Playgroud)

Mat*_*ker 6

我只是重新编辑它,亲自 - 给你的观众一些比传说中的"NA"更好的东西.

# Recoding is easier with this off. When you want a factor, you'll know.
options(stringsAsFactors = FALSE)

library(ggplot2)

# Set up the data.frame
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)


# Convert NAs to "Unknown"
df$gender[is.na(df$gender)] <- "Unknown"



ggplot(df, aes(x=gender, fill=gender)) +
  geom_bar() + 
  labs(x=NULL, y="Frequency") +
  scale_fill_manual("Gender", values=c("red", "blue", "black"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mat*_*ker 5

如果您确实必须按原样使用您的NA,则可以将性别纳入不排除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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

NA仍未显示在图例中 - ggplot不希望在此处绘制NA,这就是为什么通常更容易重新编码它们,就像我在其他答案中那样.无论哪种方式,我认为你将不得不修改你的性别变量.