8

我想绘制一个条形图,其中显示了男性、女性和 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"))
4

2 回答 2

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

在此处输入图像描述

于 2013-09-23T23:40:32.437 回答
6

如果你真的必须让你的 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"))

在此处输入图像描述

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

于 2013-09-23T23:59:24.703 回答