Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calendar heat map tetris chart

Tags:

r

ggplot2

So I was reading this post and I fell a little in love with the calendar heat map with Tetris-style month breaks.

However, the ggplot example doesn't implement the Tetris breaks, which are arguably the best part.

So, FTFY, gist here:

results

The procedure for this is:

  1. create appropriate Tetris breaks for your data
  2. left_join your data to the Tetris breaks created in (1)
  3. pump the above through ggplot with some specially crafted geoms

The methodology for (1) is reasonably straightforward, implemented in the calendar_tetris_data(...) function in the gist, though it would be nice to make it a little more flexible.

My question is mainly around (3): how do I bundle up the 7 geoms necessary to make the breaks into a single procedure or geom?

If I do this:

calendar_tetris_geoms <- function() {
  geom_segment(aes(x=x, xend=x, y=ymin, yend=ymax)) +                    # (a)
    geom_segment(aes(x=xmin, xend=xmax, y=y, yend=y)) +                  # (b)
    geom_segment(aes(x=dec.x, xend=dec.x, y=dec.ymin, yend=dec.ymax)) +  # (c)
    geom_segment(aes(x=nye.xmin, xend=nye.xmax, y=nye.y, yend=nye.y)) +  # (d)
    geom_segment(x=-0.5, xend=51.5, y=7.5, yend=7.5) +                   # put a line along the top
    geom_segment(x=0.5, xend=52.5, y=0.5, yend=0.5) +                    # put a line along the bottom
    geom_text(aes(x=month.x, y=month.y, label=month.l), hjust=0.25)      # (e)

}

And then try to add that to my ggplot, it doesn't work:

> ggplot(data) + calendar_tetris_geoms()
Error in calendar_tetris_geoms() : 
  argument "plot" is missing, with no default

I clearly don't understand how this works. How does this work?

like image 963
dvmlls Avatar asked Nov 18 '14 17:11

dvmlls


1 Answers

Modifying @baptiste's suggestion, if I do this:

calendar_tetris_geoms <- function() {
  list(
    geom_segment(aes(x=x, xend=x, y=ymin, yend=ymax)),                 # (a)
    geom_segment(aes(x=xmin, xend=xmax, y=y, yend=y)),                 # (b)
    geom_segment(aes(x=dec.x, xend=dec.x, y=dec.ymin, yend=dec.ymax)), # (c)
    geom_segment(aes(x=nye.xmin, xend=nye.xmax, y=nye.y, yend=nye.y)), # (d)
    geom_segment(x=-0.5, xend=51.5, y=7.5, yend=7.5),                  # put a line along the top
    geom_segment(x=0.5, xend=52.5, y=0.5, yend=0.5),                   # put a line along the bottom
    geom_text(aes(x=month.x, y=month.y, label=month.l), hjust=0.25)    # (e)
  )
}

Then this works a treat:

calendar_tetris_data(min(stock.data$date), max(stock.data$date)) %>% 
  left_join(stock.data) %>% 
  ggplot() + 
  geom_tile(aes(x=week, y=wday2factor(wday), fill = Adj.Close), colour = "white") + 
  calendar_tetris_geoms() + 
  facet_wrap(~ year, ncol = 1)
like image 175
dvmlls Avatar answered Oct 07 '22 06:10

dvmlls