【问题标题】:How to get clustered Stack bar in R?如何在 R 中获得聚集的堆栈栏?
【发布时间】: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


【解决方案1】:

正如人们在 cmets 中提到的那样,geom_bar 旨在无需 y 输入即可工作。拥有y = id 意味着您将 y 值设置为所有 ID 的总和,这不是您想要的。 geom_bar 使用 stat_count 而不是 stat_identity 在幕后进行计数,然后将其映射到您的 y 值。

所以你可以让一切变得非常简单——没有,没有统计——让geom_bar为你设置。

library(ggplot2)
library(reshape2)

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)


melted <- melt(df, id.vars = c('id','pre_post'))


ggplot(melted, aes(x = pre_post, fill = value)) +
    geom_bar(position = "stack") +
    facet_grid(~ variable)

我做了第二个例子,因为你提到显示每个答案的频率。您可以调用stat_count 为标签制作文本几何图形。请注意,calc(count)..count.. 的新替代品,尽管新语法可能仅在 ggplot2 的 github 版本中。

ggplot(melted, aes(x = pre_post, fill = value)) +
    geom_bar(position = "stack") +
    stat_count(aes(label = calc(count)), geom = "text", position = position_stack(vjust = 0.5)) +
    facet_grid(~ variable)

reprex package (v0.2.0) 于 2018 年 4 月 17 日创建。

【讨论】:

  • 哦...太棒了...+1 用于堆栈中的计数。 @卡米尔
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2022-07-07
  • 2020-04-12
相关资源
最近更新 更多