使用 ggplot 出现堆积柱形图而不是躲避

Stacked column chart appearing instead of dodged using ggplot

我正在尝试创建一个柱形图,其中有一个变量 "Hall" 表示他们跨月的总计。我在代码方面得到了一些帮助,但我 运行 它将所有大厅放在彼此之上作为堆叠柱形图而不是闪避。有什么想法吗?

这是我试过的方法。

library(tidyverse)
fall2 <- structure(list(Hall = c("1959E", "1959E", "1959E", "1959E", "1959E", 
 "2109 F", "2109 F", "2109 F", "2109 F", "2109 F"), Month = c("August", 
 "December", "November", "October", "September", "August", "December", 
 "November", "October", "September"), total = c(2, 4, 5, 11, 8, 
 1, 3, 8, 7, 4)), row.names = c(NA, -10L), class = c("grouped_df", 
 "tbl_df", "tbl", "data.frame"), vars = "Hall", drop = TRUE, indices = list(
 0:4, 5:9), group_sizes = c(5L, 5L), biggest_group_size = 5L, labels =
 structure(list(Hall = c("1959E", "2109 F")), row.names = c(NA, -2L), 
 class = "data.frame", vars = "Hall", drop = TRUE))

fall2$Month <- fall2$Month %>% 
  fct_relevel("August", "September", "October", "November", "December")

fall2 <- fall2 %>%
  arrange(Month, -total) %>%
  mutate(order = row_number())

#something like this?
ggplot(fall2, aes(order, total)) + 
  geom_col(aes(fill = total), position = "dodge") +
  guides(fill=FALSE) + 
  ggtitle("Fall Events by Hall") +
  facet_wrap(~Month, nrow = 1, scales = "free_x") +
  scale_x_continuous(breaks = fall2$order, labels = fall2$Hall,expand = c(0,0))

我希望它看起来像每个月有 2 个大厅,而不是堆叠在一起。感觉应该是小错误吧

ggplot 需要一个分类变量来躲避。在这里,我将 group = Hall 添加到 aes 以告诉它按霍尔值躲闪:

ggplot(fall2, aes(order, total)) + 
  geom_col(aes(fill = total, group = Hall), position = "dodge") +
  guides(fill=FALSE) + 
  ggtitle("Fall Events by Hall") +
  facet_wrap(~Month, nrow = 1, scales = "free_x") +
  scale_x_continuous(breaks = fall2$order, labels = fall2$Hall,expand = c(0,0))

如您所见,我们仍然在 x 轴上得到重叠的标签。您的代码显示 breaks = fall2$order, labels = fall2$Hall,使 x 轴标签处于唯一的 order 值并使用相应的 Hall 值标记它们。查看您的数据:

fall2
# A tibble: 10 x 4
# Groups:   Hall [2]
   Hall   Month     total order
   <chr>  <fct>     <dbl> <int>
 1 1959E  August        2     1
 2 2109 F August        1     1
 3 1959E  September     8     2
 4 2109 F September     4     2
 ...

我们可以看到每个 order 值都有多个 Hall 值---所以 ggplot 正在做你要求它做的事情。在 order = 1 处,我们得到相应的 Hall 标签:"1959E"2109 F(第 1 行和第 2 行)。

我不太确定你为什么要使用 order...似乎毫无意义。如果我们改为将 Hall 放在 x 轴上(并进行一些其他相关更改,则不再需要 group,也不需要指定标签,也不需要 position "dodge"。但我们需要一个 discrete 不是 continuous x 比例),事情变得更简单,看起来更好。

ggplot(fall2, aes(Hall, total)) + 
  geom_col(aes(fill = total), width = 1) +
  guides(fill=FALSE) + 
  ggtitle("Fall Events by Hall") +
  facet_wrap(~Month, nrow = 1, scales = "free_x") +
  scale_x_discrete(expand = c(0,0))