Reputation: 133
I have data as an ordered factor, with levels 1,2,3,4,5. (This is Likert scale data.) I would like to use ggplot to create a bar chart of counts, but this must include all the levels, even the ones with zero count. Here is an example data frame with zero count at the level equal to 2.
library(ggplot2)
foo <- structure(list(feed.n.1.50..3. = structure(c(4L, 4L, 4L, 4L,
4L, 5L, 5L, 4L, 1L, 1L,1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 5L, 5L, 4L, 5L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
5L, 3L, 4L, 4L, 3L, 4L, 4L, 3L, 4L, 5L, 4L, 4L, 4L, 4L), .Label = c("1",
"2", "3", "4", "5"), class = c("ordered", "factor"))), .Names = "answers", row.names = c(NA,
-50L), class = "data.frame")
table(foo) # satisfy myself the level 2 has zero entries
ggplot(foo,aes(answers)) + geom_bar(stat="bin") # stat="bin" is not needed, but there for clarity
stat_bin()
has a parameter drop
, documented as
drop: If TRUE, remove all bins with zero counts
The default is FALSE, though, so I expected the levels to be kept. Is there a simple way to use ggplot to keep all the levels of the factor?
Upvotes: 3
Views: 408
Reputation: 98429
Dropping of level is done by scales (default), so use scale_x_discrete()
with argument drop=FALSE
to show all levels.
ggplot(foo,aes(answers)) + geom_bar()+
scale_x_discrete(drop=FALSE)
Upvotes: 6