【发布时间】:2018-04-16 18:57:49
【问题描述】:
我有一个包含以下数据的数据集(比如说):
n=50
df = data.frame(id =c(seq(1,n),seq(1,n)), pre_post = c(rep(0,n),rep(1,n)), q1 = sample(1:5,2*n, replace = TRUE), q2 = sample(1:5,2*n, replace = TRUE),q3 = sample(1:5,2*n, replace = TRUE),q4 = sample(1:5,2*n, replace = TRUE))
df$pre_post = as.factor(df$pre_post)
df$q1 = as.factor(df$q1)
df$q2 = as.factor(df$q2)
df$q3 = as.factor(df$q3)
df$q4 = as.factor(df$q4)
head(df)
我想要一个图表,使得所有问题都应该在 x 轴上,并且堆栈应该是对 pre 和 post 回答为 1、2、...5 的人数。
如何做到这一点?
我有 10 个这样的问题,我需要将它们绘制在一个图表中。
通常想要比较每个因素在前后的每个问题的频率。
我做了什么?
melted = melt(df, id.vars = c('id','pre_post'))
ggplot(melted, aes(x = pre_post, y =id , fill = value)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~variable)
这给了我以下情节。但是这个图表似乎不正确。我哪里错了?
【问题讨论】:
-
可能需要分面:
https://stackoverflow.com/questions/47085795/clustered-and-stacked-bar-plot-with-multiple-csv-files -
"但这张图似乎不正确。"不正确怎么办?您期望或需要它看起来像什么?
-
观察次数是50只知道..但它显示更多。 @卡米尔
-
y不应该是id。将y留空。还要删除stat = "identity",因为您想要计数数据 -
@gloom 我明白了——试试
ggplot(melted, aes(x = pre_post, fill = value)) + geom_bar(position = 'stack') + facet_grid(~variable)。在这种情况下,根本没有y参数,因为您只是想要(据我了解)每个x中每个variable中的value列的计数。
标签: r ggplot2 data-analysis