我想显示不同子组在几个月内的变量总数

时间:2019-03-22 20:39:35

标签: r ggplot2 dplyr

我想使用ggplot2dplyr来创建一个图表,以显示我们的展厅在几个月内的表现。因此,从8月至12月,我希望看到三个大厅中每个大厅的三个酒吧及其总数。

我已经准备好数据了,但是我不知道如何使用ggplot2包来放置它。

#Events by Hall
fall2 <- fall %>% 
  group_by(Hall,Month) %>%
  summarize(total = sum(Count))

#something like this?
ggplot(Fall2, aes(Hall, Month)) + 
  geom_col(aes(fill = total), position = "dodge") +
  guides(fill=FALSE) + 
  ggtitle("Fall Events by Hall")

这是我的数据

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

最后,我希望x轴显示各个月,并在每个月内将其分解为“霍尔”。理想情况下,如果以Count降序最好。

1 个答案:

答案 0 :(得分:2)

编辑:修改为按每月Count的降序排列,具体取决于此处的技术:https://drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets

您可能希望按月排序。目前,它们是一个字符变量,将按字母顺序排序。这里的fct_relevel行使它们成为有序因子,以便ggplot知道要使用的顺序。 (顺便说一句,转换它们的方式可能不那么手动,但是我不知道是副手...)

# library(tidyverse)  # Loads all three and a few more
library(dplyr); library(forcats); library(ggplot2)
fall2$Month <- fall2$Month %>% fct_relevel("August", "September", "October", "November", "December")
fall2 <- fall2 %>%
  ungroup() %>%    # EDIT -- source data grouped
  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))

enter image description here