samot79 samot79 - 26 days ago 7
R Question

Compare year to year revenue

I am trying to create a plot to compare year to year revenue, but I can't get it to work and don't understand why.

Consider my df:

df <- data.frame(date = seq(as.Date("2016-01-01"), as.Date("2017-10-01"), by = "month"),
rev = rnorm(22, 150, sd = 20))

df %>%
separate(date, c("Year", "Month", "Date")) %>%
filter(Month <= max(Month[Year == "2017"])) %>%
group_by(Year, Month) %>%
ggplot(aes(x = Month, y = rev, fill = Year)) +
geom_line()
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?


I don't really understand why this isn't working. What I want is two lines that go from January to October.

Answer Source

this should work for you:

library(tidyverse)
df <- data.frame(date = seq(as.Date("2016-01-01"), as.Date("2017-10-01"), by = "month"),
                 rev = rnorm(22, 150, sd = 20))

df %>% 
  separate(date, c("Year", "Month", "Date")) %>% 
  filter(Month <= max(Month[Year == "2017"]))  %>%
  ggplot(aes(x = Month, y = rev, color = Year, group = Year)) + 
  geom_line()

it was just the grouping which gone wrong due to the type of variables, it might be usefull if you use lubridate for the dates (also a tidyverse package)

library(lubridate)
df %>% 
  mutate(Year = as.factor(year(date)), Month = month(date)) %>% 
  filter(Month <= max(Month[Year == "2017"])) %>% 
  ggplot(aes(x = Month, y = rev, color = Year)) + 
  geom_line()