Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我如何使用ggplot2和stat_bin制作一个条形图,其中包含没有观测值的数字级别_R_Ggplot2 - Fatal编程技术网

R 我如何使用ggplot2和stat_bin制作一个条形图,其中包含没有观测值的数字级别

R 我如何使用ggplot2和stat_bin制作一个条形图,其中包含没有观测值的数字级别,r,ggplot2,R,Ggplot2,我将数据作为有序因子,级别为1,2,3,4,5。(这是利克特刻度数据。)我想使用ggplot创建计数条形图,但这必须包括所有级别,即使是计数为零的级别。下面是一个示例数据帧,其零计数级别等于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,

我将数据作为有序因子,级别为1,2,3,4,5。(这是利克特刻度数据。)我想使用ggplot创建计数条形图,但这必须包括所有级别,即使是计数为零的级别。下面是一个示例数据帧,其零计数级别等于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

不过,默认值为FALSE,因此我希望保持这些级别。有没有一种简单的方法可以使用ggplot来保持因子的所有级别?

级别的下降是按比例进行的(默认),因此使用
scale\u x\u discrete()
和参数
drop=FALSE
来显示所有级别

ggplot(foo,aes(answers)) + geom_bar()+
  scale_x_discrete(drop=FALSE)

+1。即使您使用的是
qplot
,也可以这样做——只需在qplot调用结束后添加
scale\u x\u discrete
ggplot(foo,aes(answers)) + geom_bar()+
  scale_x_discrete(drop=FALSE)