简体   繁体   English

如何使用ggplot2绘制NA栏

[英]How to plot NA bar with ggplot2

I want to plot a bar chart where the count of males, females and NAs is shown. 我想绘制一个条形图,其中显示了男性,女性和NA的数量。 The problem is that when I add the option fill=gender for colouring the bars I lose the NA bar. 问题是,当我添加选项fill=gender以使条纹着色时,我会丢失NA条。 What option should I use to keep the NA bar also with colours? 我应该使用什么选项来保持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"))

I'd just recode it, personally - give your audience something nicer than "NA" in the legend. 我只是重新编写它,个人 - 给你的观众一些比传说中的“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"))

在此输入图像描述

If you really have to have your NAs as they are, you can make gender into a factor that doesn't exclude NA: 如果您确实必须按原样使用您的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 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. NA仍未显示在图例中 - ggplot不希望在这里绘制NA,这就是为什么通常更容易重新编码它们,就像我在其他答案中那样。 Either way, I think you're going to have to modify your gender variable. 无论哪种方式,我认为你将不得不修改你的性别变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM