ggplot2因子变量na

时间:2015-10-20 16:33:10

标签: r ggplot2

我正在尝试使用ggplot2将因子变量绘制为条形图。

我创建了这样的变量:

survey$coffeeblack2[survey$coffee == 1] <- 2
survey$coffeeblack2[survey$coffee == 2] <- 1
survey$coffeeblack2[survey$coffee == 3] <- 1
survey$coffeeblack2[survey$coffee == 4] <- 1
survey$coffeeblack2[survey$coffee == 5] <- 0
survey$coffeeblack2[survey$coffee == 6] <- 1
survey$coffeeblack2[survey$coffee == "NA"] <- NA

survey$coffeeblack2 <- as.factor(survey$coffeeblack2)
summary(survey$coffeeblack2)

此摘要命令提供以下正确的输出:

0    1    2     NA's 
139  186  107    4

我使用以下命令绘制它:

ggplot(survey, aes(coffeeblack2)) + 
  geom_bar( aes(fill=..count..)) + 
  scale_fill_gradient("Count", low="green", high ="red") + 
  scale_x_discrete(labels = c("0" = "Non-Drinker", "1" = "Adder", "2" = "Black", "NA" = "NA"))

它提供以下输出:

enter image description here

NA的标绘但被标记为“非饮酒者”。我想出了如何从图表中删除它们,但是如何将它们正确地标记为NA?

(我也删除了

, "NA" = "NA"

得到了相同的结果)

更新了最小的工作示例:

library(ggplot2)
a <- c(1,2,2,3,3,3,NA,NA)
a.f <- as.factor(a)
summary(a.f)  

ggplot(as.data.frame(a.f), aes(a.f)) + geom_bar( aes(fill=..count..)) +  scale_x_discrete(labels = c("1" = "One", "2" = "Two", "3" = "Three", "NA" = "NA")) 

Example two

该示例显示在绘制NAs时显示“One”

2 个答案:

答案 0 :(得分:0)

设置ggplot的因子标签

survey$coffeeblack2 <- as.factor(survey$coffeeblack2
    levels=c(0,1 ,2 ), # the values found in the first argument
    labels=c("Non-Drinker",  "Adder",  "Black")) # the labels to apply to those values

让ggplot使用数据中的标签:

ggplot(survey, aes(coffeeblack2)) + 
  geom_bar( aes(fill=..count..)) + 
  scale_fill_gradient("Count", low="green", high ="red")

这是图形语法的特定目的之一 - 将数据操作(将标签与值匹配)与数据特征到绘图特征的映射(即数据标签到轴标签)分开。

答案 1 :(得分:0)

#some data
DF <- iris
DF[8:10, "Species"] <- NA
DF$Species <- as.character(as.integer(DF$Species))

像这样设置breakslabels

library(ggplot2)
summary(DF$Species)
ggplot(DF, aes(x = Species)) + 
  geom_bar( aes(fill=..count..)) + 
  scale_fill_gradient("Count", low="green", high ="red") + 
  scale_x_discrete(breaks = c("1", "2", "3", NA),
                   labels = c("Non-Drinker", "Adder", "Black", "NA"))

resulting plot