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

时间:2019-03-28 22:28:41

标签: r ggplot2 dplyr forcats

我正在尝试创建一个柱形图,该柱形图的变量“ 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))

我希望每个月看起来像两个大厅,而不是堆放。我觉得这应该是一个小错误。

1 个答案:

答案 0 :(得分:1)

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))

enter image description here

如您所见,我们仍然在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"。但是我们需要{{1 }},而不是discrete x比例尺),事情变得更简单,看起来更好。

continuous

enter image description here