2020-03-08

Calendar heatmap by hour and weekday in ggplot2

Problem

We want to create a calendar heatmap using ggplot2.

Solution

In our example we generate random dates, and then group the results by hour of the day and day of the week.

library(tidyverse)
library(lubridate)
# Data
set.seed(2020)
df <-
  data.frame(dates = sample(seq(
    as.POSIXct('2019/01/01', tz = "CET"),
    as.POSIXct('2019/12/31', tz = "CET"),
    by = "sec"
  ), 1000))

# Data manipulation
df %>%
  mutate(days = factor(weekdays(dates, abbreviate = TRUE),
                       levels = rev(
                         c('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
                       ))) %>%
  group_by(hours= hour(dates), days) %>%
  summarise(sessions = n()) %>%

# Plot
ggplot(aes(hours, days)) +
  geom_tile(aes(fill = sessions), colour = "white") +
  scale_fill_distiller(palette = "YlGnBu", direction = 1) +
  scale_x_continuous(breaks = 0:23) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.key.width = unit(2, "cm"),
    panel.grid = element_blank()
  ) +
  coord_equal()

Results

Related posts

References

No hay comentarios:

Publicar un comentario

Nube de datos