gpt4 book ai didi

r - 如何使用 ggplot2 绘制 NA 条

转载 作者:行者123 更新时间:2023-12-04 06:39:19 25 4
gpt4 key购买 nike

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

最佳答案

我只是个人重新编码 - 给你的观众比传说中的“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"))

enter image description here

关于r - 如何使用 ggplot2 绘制 NA 条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com