adlisval adlisval - 1 month ago 6
R Question

R plot months for the first 2 years

I have a data frame with data for max 2 years period on different objects:

ISBN Date Quantity
3457 2004-06-15 10
3457 2004-08-16 6
3457 2004-08-19 10
3457 2005-04-19 7
3457 2005-04-20 12
9885 2013-01-15 10
9885 2013-03-16 6
9855 2013-08-19 10
9885 2014-09-19 7
9885 2014-09-20 12


How can I plot
Jan to Dec
for the 1st year, continued by
Jan to Dec
for the 2nd year?
I guess the idea is to normalize the years (to have 1st, 2nd), but not the months. (here's an example)
Number of Items Sold over 2 Years Period Since Release

Answer

You could try:

data <- df %>%
  group_by(ISBN) %>%
  arrange(Date) %>%
  mutate(Year  = year(Date), 
         Month = month(Date, label = TRUE),
         Rank  = paste(sapply(cumsum(Year != lag(Year,default=0)), toOrdinal), "Year")) %>%
  group_by(Rank, Month, add = TRUE) %>%
  summarise(Sum = sum(Quantity))

ggplot(data = data, aes(x = Month, y = Sum, 
                        group = factor(ISBN), 
                        colour = factor(ISBN))) +
  geom_line(stat = "identity") +
  facet_grid(. ~ Rank) +
  scale_colour_discrete(name = "ISBN") +
  theme(panel.margin = unit(0, "lines"),
        axis.text.x = element_text(angle = 90))

Aussming the following df:

df <- data.frame(
  ISBN = sample(c(3457, 9885), 1000, replace = TRUE),
  Date = as.character(sample(seq(as.Date('2004/01/01'), 
                                 as.Date('2011/12/31'), by = "month"), 
                             1000, replace = TRUE)),
  Quantity = sample(1:12, 1000, replace = TRUE)
)

This would produce:

enter image description here

Comments