I am trying to plot a factor variable as a bar plot using ggplot2
.
I create the variable like this:
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)
This summary command gives the following, correct, output:
0 1 2 NA's
139 186 107 4
I use the following command to plot it:
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"))
It gives the following output:
The NA's plotted but are labelled "Non-Drinker." I figured out how to remove them from the graph, but how do I get them correctly labelled as NA?
(I also removed the
, "NA" = "NA"
and got the same result)
Updated with minimal working example:
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"))
The example shows it says "One" when plotting the NAs