Mostrando entradas con la etiqueta scale_fill_distiller. Mostrar todas las entradas
Mostrando entradas con la etiqueta scale_fill_distiller. Mostrar todas las entradas

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

2018-03-13

Generar un mapa de calor por días y horas con ggplot2

Problema

Queremos crear un mapa de calor, con teselas coloreadas en función de la frecuencia en ggplot2.

Solución

library(dplyr)
library(lubridate)
library(ggplot2)

# Generamos fechas aleatorias
set.seed(2015)
df <-
  data.frame(fechas = sample(seq(
    as.POSIXct('2018/01/01', tz = "CET"),
    as.POSIXct('2018/12/31', tz = "CET"),
    by = "sec"
  ), 1000))

# Manipulamos el data frame 
# 1. Cambiamos el nombre de los días de la semana
# 2. Agrupamos por horas y días
df %>%
  mutate(Días = factor(
    weekdays(fechas),
    levels = rev(
      c(
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
        "Sunday"
      )
    ),
    labels = c(
      "Domingo",
      "Sábado",
      "Viernes",
      "Jueves",
      "Miércoles",
      "Martes",
      "Lunes"
    )
  )) %>%
  group_by(Horas = hour(fechas), Días) %>%
  summarise(Sesiones = n()) %>%
# Creamos el gráfico
  ggplot(aes(Horas, Días)) +
  geom_tile(aes(fill = Sesiones), 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()

Resultado

Referencias

Nube de datos