gpt4 book ai didi

r - 如何使用 ggplot2 和 stat_bin 制作包含数字级别但没有观察值的条形图

转载 作者:行者123 更新时间:2023-12-01 10:51:09 24 4
gpt4 key购买 nike

我将数据作为有序因子,级别为 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

stat_bin()有一个参数drop,记录为

drop: If TRUE, remove all bins with zero counts

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

最佳答案

级别的下降是由比例(默认)完成的,因此使用带有参数 drop=FALSEscale_x_discrete() 来显示所有级别。

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

enter image description here

关于r - 如何使用 ggplot2 和 stat_bin 制作包含数字级别但没有观察值的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20016617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com