1

假设我有 1 个问题,有 8 个选项。受访者可以选择最少 1 个选项和最多 2 个选项。我为每个选择编写了一个假人。

现在很容易使用 ggplot 绘制 8 个图形,其中每个图形包含是和否条形图。但是我的问题是如何使用 ggplot 来创建一个删除所有否并只保留是的图(所以在我的情况下,图表应该有 8 个是栏)

respondant1 = c("yes","no","no","no","no","no","no","yes")
respondant2 = c("yes","no","no","no","no","no","no","yes")
respondant3 = c("no","no","no","no","yes","no","no","no")
respondant4 = c("no","yes","no","no","no","yes","no","no")
respondant5 = c("no","no","yes","no","no","no","no","no")
respondant6 = c("no","yes","no","no","no","no","no","no")
respondant7 = c("no","no","no","no","no","no","yes","yes")
respondant8 = c("no","no","no","yes","no","no","no","no")

new = rbind(respondant1,respondant2,respondant3,respondant4,
            respondant5,respondant6,respondant7,respondant8)

new = as.data.frame(new)
4

1 回答 1

1

转换为因子(第一行)不是必需的,但是,因子是响应的合适数据结构。剩下要做的就是汇总正分数,并使用geom_barwith stat=identity

new[] <- lapply(new, function(x) factor(x, levels = c('yes', 'no')))
yes_plot <- data.frame(question=colnames(new), 
                       yes=sapply(new, function(x) sum(x == 'yes')))
ggplot(yes_plot, aes(question, yes)) + geom_bar(stat='identity')

在此处输入图像描述

于 2014-06-23T07:48:57.013 回答