0

I'm working on a dataset about football. So I've made some time series analyses. I've calculated the amount of goals and the amount of goals in the previous month. Now I'm trying to plot it into a graph. I'm trying to make a group bar chart with the goals of a certain month and from the previous month next to it.

This is the code that I'm using:

df_eredivisie %>% 
  group_by(month= month(date, label = TRUE)) %>% 
  summarise(goals = sum(FTHG + FTAG)) %>% 
  mutate(last = lag(goals, 1))

So this is the result (Sorry can't post pictures :/ ):

month goals last
Jan 69  NA      
Feb 121 69      
Mar 116 121     
Apr 155 116     
May 78  155     
Aug 88  78      
Sep 124 88      
Oct 91  124     
Nov 91  91      
Dec 128 91

Could someone help me with the grouped bar chart? I've tried to combine the columns, so I could do fill and have the goals and last with different colours. But I couldn't figure out how to do that.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • You can try facet_wrap() or facet_grid(). Try https://stackoverflow.com/questions/25690208/layered-axes-in-ggplot/25702640#25702640 for more details – Mohit Jun 07 '20 at 08:27
  • Hi Bart, you could share with us the result of the `dput` function on `(head(df_eredivisie, 30)` or on the result of your code above. This way, we can help you by trying out some real code. Also, please try to add an expected output, so we are sure to answer the question correctly. However, you might be looking for `tidyr::pivot_longer`. – Dan Chaltiel Jun 07 '20 at 08:30

1 Answers1

2

Your data need to be in long format, then it's simple:

library(ggplot2)
library(tidyverse)

df <- tribble(~month, ~goals, ~last,
              "Jan",  69,     NA,
              "Feb",  121,    69,
              "Mar",  116,    121,
              "Apr",  155,    116,
              "May",  78,     155,
              "Aug",  88,     78,
              "Sep",  124,    88,
              "Oct",  91,     124,
              "Nov",  91,     91,
              "Dec",  128,    91)

df %>% 
  pivot_longer(cols = 2:3, names_to = "category") %>% 
  mutate(month = factor(month, levels = month.abb)) %>% 
  ggplot(aes(x = month, y = value, fill = category)) +
  geom_col(position = "dodge")
#> Warning: Removed 1 rows containing missing values (geom_col).

Created on 2020-06-07 by the reprex package (v0.3.0)

If you reverse the factors, it looks like this:

df %>% 
  pivot_longer(cols = 2:3, names_to = "category") %>% 
  mutate(month = factor(month, levels = month.abb)) %>% 
  ggplot(aes(x = month, y = value, fill = forcats::fct_rev(category))) +
  geom_col(position = "dodge")
#> Warning: Removed 1 rows containing missing values (geom_col).

Created on 2020-06-07 by the reprex package (v0.3.0)

So it works, but the second column does not add any information, as you can see the previous month right next to it...

ek-g
  • 681
  • 3
  • 7