轴切换的条形图调查结果

Barplotting survey results with axes switched

我的 R 专业知识水平是 25% 到 "R for Everyone",这不足以完成我的第一个实际任务:

48 people were asked to memorize and recall 10 digits. Now the results should be presented in a bar plot with the number of responses on the X axis and the number of memorized digits - on Y.


这是我现在所做的:

responses <- c(10,10,10,10,10,10,10,10,10,10,3,3,3,3,3,3,3,3,3,3,3,5,5,5,5,5,5,5,2,2,2,2,2,2,6,6,6,6,8,8,8,8,4,4,4,7,7,9)
# 10 people recalled 10 digits, 11 people - 3 digits, 7 people 5 digits, etc

我试过了plot(responses)。生成的图形完全偏离了我的目标。

我尝试了qplotbarplot,但我不知道如何切换坐标轴(不是让图表水平,而是交换X和Y)。

然后我想我应该把responses当作一个因素。但是ggplot2 doesn't know how to deal with data of class factor。另外,我不知道如何表述“在 X 轴上显示因子级别,在 Y 上显示每个级别的深度”。

然后我将 responses 转换为单列 data.frame,结合 ggplot2,得到了几乎令人满意的结果:

df <- data.frame(responses)
ggplot(df, aes(df$responses)) + geom_bar(binwidth=.5,fill="#56B4E9") + xlab("Digits memorized") +    ylab("# of responses") + ggtitle("10 digit memorization experiment results") + scale_x_continuous( breaks = round( seq( min(df$responses), max(df$responses), by = 1 ), 1) ) + theme_economist() + scale_y_continuous(breaks = c(0:11)) + theme(axis.title=element_text(size=14))

为什么这张图不是我需要的:

在上面的代码中,我很乐意将 ggplot(df, aes(df$responses)) 替换为 ggplot(df, aes(df$something_else)),但是 responses 列是我所有的。


我试过了。你在上面看到的是我过去 3 天一直在尝试的东西的影子。不幸的是,我的大部分尝试都归结为跟随我自己的足迹进入同样的死胡同。

我搜索了。我发现了两类解决方案:要么用于多个 columns/variables,我不明白如何将其应用于我的单列 data.frame;或者那些假设更多知识的人。

如有任何提示,我将不胜感激。

感谢您的耐心等待。

您可以使用基本图形函数 barplot()

barplot(table(responses), horiz=T, xlab="Count",ylab="Digits Mem")

或 ggplot 与 coord_flip()

ggplot(data.frame(resp=factor(responses)), aes(resp)) + 
    geom_bar() + coord_flip() +
    ylab("Count") + xlab("Digits Mem")

类似于这个朴素的直方图?

responses <- c(10,10,10,10,10,10,10,10,10,10,3,3,3,3,3,3,3,3,3,3,3,5,5,5,5,5,5,5,2,2,2,2,2,2,6,6,6,6,8,8,8,8,4,4,4,7,7,9)
df <- data.frame(responses  = responses)

图书馆("ggthemes")

ggplot(data = df, aes(x = responses)) +
  geom_histogram(stat = "bin", color = "blue") +
  theme_tufte() +
  labs(x = "Digits Memorized", y = "Number of Subjects") +
  ggtitle("Count of Participants Per Digits Memorized") +
  annotate("segment", x = 4.5, xend = 8.5, y = 5.646, yend = 5.646, width =3) +
  annotate("text", x = 6.5, xend = 8.5, y = 6, yend = 6, label = "Average = 5.5")