首页 > 解决方案 > 我想要一个并排的 barplor (R)

问题描述

我在 data.frame 中有两列。假设一个称为“之前”,另一个称为“之后”。这 2 个因素中的每一个都有 5 个级别(非常满意、满意、不知何故、不满意、非常不满意)。

这是数据:

dat <- structure(list(before = structure(c(2L, 5L, 5L, 1L, 3L, 3L), .Label = c("very satisfied", 
"satisfied", "somehow", "dissatisfied", "very dissatisfied"), class = "factor"), 
    after = structure(c(3L, 3L, 5L, 2L, 2L, 2L), .Label = c("very satisfied", 
    "satisfied", "somehow", "dissatisfied", "very dissatisfied"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

如何构建一个并排的情节,以便对于这 5 个级别中的每一个,有 2 个条(之前和之后)并排表示?

标签: rggplot2

解决方案


透视数据后,您可以使用position = "dodge"并排获取您的组。

dat %>%
  pivot_longer(everything(), names_to = "period", values_to = "score") %>%
  ggplot(aes(x = score, group = period, fill = period)) +
  geom_bar(position = "dodge")

推荐阅读