我有数据作为有序因子,水平1,2,3,4,5.(这是李克特量表数据.)我想用ggplot创建一个计数条形图,但这必须包括所有级别,甚至是零计数的级别.这是一个示例数据帧,其等级为零,计数为零.
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
Run Code Online (Sandbox Code Playgroud)
stat_bin()有一个参数drop,记录为
drop: If TRUE, remove all bins with zero counts
Run Code Online (Sandbox Code Playgroud)
但是,默认值为FALSE,因此我预计会保留这些级别.有没有一种简单的方法来使用ggplot来保持因子的所有级别?
通过缩放(默认)来删除级别,因此使用scale_x_discrete()参数drop=FALSE来显示所有级别.
ggplot(foo,aes(answers)) + geom_bar()+
scale_x_discrete(drop=FALSE)
Run Code Online (Sandbox Code Playgroud)
