Mostrando entradas con la etiqueta as.POSIXct. Mostrar todas las entradas
Mostrando entradas con la etiqueta as.POSIXct. Mostrar todas las entradas

2021-01-01

Cómo crear una serie temporal con intervalos de 30 minutos

Title

Problema

Queremos crear una serie temporal de intervalos de 30 minutos.

Ejemplo

[1] "2017-01-01 00:00:00 UTC"
[2] "2017-01-01 00:30:00 UTC"
[3] "2017-01-01 01:00:00 UTC"
[4] "2017-01-01 01:30:00 UTC"
[5] "2017-01-01 02:00:00 UTC"
[6] "2017-01-01 02:30:00 UTC"

Solución

Usamos la función seq y especificando los minutos en el argumento by, así como el uso horario "UTC". Tecleamos ?seq.POSIXt para obtener más detalles sobre el argumento que podemos especificar como cadena sde texto:

A character string, containing one of "sec", "min", "hour", "day", "DSTday", "week", "month", "quarter" or "year". This can optionally be preceded by a (positive or negative) integer and a space, or followed by "s".

seq(as.POSIXct("2017-01-01", tz = "UTC"),
    as.POSIXct("2017-01-02", tz = "UTC"),
    by = "30 min")

Referencias

2020-12-23

How to create a time series by 30 minute intervals

Title

Problem

We want to create a time series by 30 minute intervals.

Example

[1] "2017-01-01 00:00:00 UTC"
[2] "2017-01-01 00:30:00 UTC"
[3] "2017-01-01 01:00:00 UTC"
[4] "2017-01-01 01:30:00 UTC"
[5] "2017-01-01 02:00:00 UTC"
[6] "2017-01-01 02:30:00 UTC"

Solution

We use the function seq and specify minutes in the by argument, and pass the time zone "UTC". Type ?seq.POSIXt for more details about the by argument specified as a character string:

A character string, containing one of "sec", "min", "hour", "day", "DSTday", "week", "month", "quarter" or "year". This can optionally be preceded by a (positive or negative) integer and a space, or followed by "s".

seq(as.POSIXct("2017-01-01", tz = "UTC"),
    as.POSIXct("2017-01-02", tz = "UTC"),
    by = "30 min")

References

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

2019-02-08

Calcular y representar la duración del día con R

Problema

Queremos calcular y representar la duración del día con R en función de unas coordinadas geográficas.

Solución

  • 1. Calculamos la salida y puesta de sol
  • Primero calculamos la salida y la puesta de sol con la función getSunlightTimes del paquete suncalc. Indicamos el intervalo deseado, las coordinadas (latitud y longitud), y el huso horario (tz, time zone) correspondiente.

    library(suncalc) 
    library(tidyverse)
    library(scales)
    df <-
      getSunlightTimes(
        date = seq.Date(as.Date("2017-12-01"), as.Date("2018-12-31"), by = 1),
        keep = c("sunrise", "sunriseEnd", "sunset", "sunsetStart"),
        lat = 39.8628,
        lon = 4.0273,
        tz = "CET"
      )
    
  • 2. Gráfico de la salida y puesta de sol
  • Necesitamos manipular los datos originales para calcular la diferencia entre el inicio del día, y la salida y puesta de sol. Después representamos las dos nuevas variables usando geom_ribbon de ggplot2. Luego personalizamos los ejes y el título.

    # Amanecer/ocaso
    df %>%
      mutate(
        date = as.POSIXct(date) - 12 * 60 * 60 ,
        sunrise = sunrise - date,
        sunset =  sunset - date,
      ) %>%
      ggplot() +
      geom_ribbon(aes(x = date, ymin = sunrise, ymax = sunset),
                  fill = "#FDE725FF",
                  alpha = .8) + # "#ffeda0"
      scale_x_datetime(
        breaks = seq(as.POSIXct(min(df$date)), as.POSIXct(max(df$date)), "month"),
        expand = c(0, 0),
        labels = date_format("%b %y"),
        minor_breaks = NULL
      ) +
      scale_y_continuous(
        limits = c(0, 24),
        breaks = seq(0, 24, 2),
        expand = c(0, 0),
        minor_breaks = NULL
      ) +
      labs(
        x = "Date",
        y = "Hours",
        title = sprintf(
          "Sunrise and Sunset for %s\n%s ",
          "Toledo (Spain)",
          paste0(as.Date(range(df$date)), sep = " ", collapse = "to ")
        )
      ) +
      theme(
        panel.background = element_rect(fill = "#180F3EFF"),
        panel.grid = element_line(colour = "grey", linetype = "dashed")
      )
    
  • 3. Duración del día
  • Muy similar al gráfico anterior. Ahora solamente necesitamos calcular la duración del día day_length y representar los resultados con geom_area and geom_line.

    df %>%
      mutate(
        date = as.POSIXct(date),
        day_length = as.numeric(sunset - sunrise)
      ) %>%
      ggplot(aes(x = date, y = day_length)) +
      geom_area(fill = "#FDE725FF", alpha = .4) +
      geom_line(color = "#525252") +
      scale_x_datetime(
        expand = c(0, 0),
        labels = date_format("%b '%y"),
        breaks =  seq(as.POSIXct(min(df$date)), as.POSIXct(max(df$date)), "month"),
        minor_breaks = NULL
      ) +
      scale_y_continuous(
        limits = c(0, 24),
        breaks = seq(0, 24, 2),
        expand = c(0, 0),
        minor_breaks = NULL
      ) +
      labs(x = "Date", y = "Hours", title = "Toledo (Spain) - Daytime duration") +
      theme_bw()
    

    Entradas relacionadas

    Referencias

    2019-02-04

    Calculate and plot sunrise and sunset times with R

    Problem

    We would like to calculate and plot the sunrise and sunset times based on any location's latitude and longitude coordinates with R.

    Solution

  • 1. Compute sunrise and sunset times
  • First we calculate the sunrise and sunset times using the function getSunlightTimes from the package suncalc. We pass the desired date interval, the appropiate latitude and longitude coordinates, and time zone (tz).

    library(suncalc) 
    library(tidyverse)
    library(scales)
    df <-
      getSunlightTimes(
        date = seq.Date(as.Date("2017-12-01"), as.Date("2018-12-31"), by = 1),
        keep = c("sunrise", "sunriseEnd", "sunset", "sunsetStart"),
        lat = 39.8628,
        lon = 4.0273,
        tz = "CET"
      )
    
  • 2. Sunrise and sunset times plot
  • We need to manipulate the original data frame to calculate the difference between midnight start of day, and the sunrise and sunset times. Then we plot those two new variables using geom_ribbon from ggplot2. We further customize the axes, and title.

    # Sunrise/set
    df %>%
      mutate(
        date = as.POSIXct(date) - 12 * 60 * 60 ,
        sunrise = sunrise - date,
        sunset =  sunset - date,
      ) %>%
      ggplot() +
      geom_ribbon(aes(x = date, ymin = sunrise, ymax = sunset),
                  fill = "#FDE725FF",
                  alpha = .8) + # "#ffeda0"
      scale_x_datetime(
        breaks = seq(as.POSIXct(min(df$date)), as.POSIXct(max(df$date)), "month"),
        expand = c(0, 0),
        labels = date_format("%b %y"),
        minor_breaks = NULL
      ) +
      scale_y_continuous(
        limits = c(0, 24),
        breaks = seq(0, 24, 2),
        expand = c(0, 0),
        minor_breaks = NULL
      ) +
      labs(
        x = "Date",
        y = "Hours",
        title = sprintf(
          "Sunrise and Sunset for %s\n%s ",
          "Toledo (Spain)",
          paste0(as.Date(range(df$date)), sep = " ", collapse = "to ")
        )
      ) +
      theme(
        panel.background = element_rect(fill = "#180F3EFF"),
        panel.grid = element_line(colour = "grey", linetype = "dashed")
      )
    
  • 3. Daytime duration
  • Very similar to the preceding plot. This time we only need to calculate the day_length and plot the results using geom_area and geom_line.

    df %>%
      mutate(
        date = as.POSIXct(date),
        day_length = as.numeric(sunset - sunrise)
      ) %>%
      ggplot(aes(x = date, y = day_length)) +
      geom_area(fill = "#FDE725FF", alpha = .4) +
      geom_line(color = "#525252") +
      scale_x_datetime(
        expand = c(0, 0),
        labels = date_format("%b '%y"),
        breaks =  seq(as.POSIXct(min(df$date)), as.POSIXct(max(df$date)), "month"),
        minor_breaks = NULL
      ) +
      scale_y_continuous(
        limits = c(0, 24),
        breaks = seq(0, 24, 2),
        expand = c(0, 0),
        minor_breaks = NULL
      ) +
      labs(x = "Date", y = "Hours", title = "Toledo (Spain) - Daytime duration") +
      theme_bw()
    

    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

    2018-03-11

    Generar fechas aleatorias entre dos momentos en el tiempo con R

    Problema

    Deseamos generar un vector con fechas aleatorias entre dos momentos en el tiempo.

    Solución

    • Opción 1: fechas
    • Con la función seq generamos una secuencia de fechas en incrementos de un día entre los dos momentos en el tiempo . Y posteriormente seleccioamos aleatoriamente 10.

      set.seed(1984)
      sample(seq(as.Date('2015-01-01'), as.Date('2017-01-01'), by = "day"), 10)
      
    • Opción 2: fechas, horas, minutos y segundos.
    • Si necesitamos, además de las fechas, generar horas, minutos y segundos aleatorios, usamos as.POSIXct, y cambiamos el incremento especificando segundos (by = "sec") en la secuencia.

      set.seed(1984)
      sample(seq(as.POSIXct('2015-01-01'), as.POSIXct('2017-01-01'), by = "sec"), 10)
      

    Resultados

  • Opción 1
  • [1] "2016-04-27" "2015-11-16" "2015-09-30" "2015-08-30" "2016-06-20"
    [6] "2016-09-19" "2015-01-24" "2015-11-21" "2016-08-23" "2015-06-05"
    
  • Opción 2
  • [1] "2016-04-26 15:04:13 CEST" "2015-11-16 10:17:23 CET" 
     [3] "2015-09-30 22:50:41 CEST" "2015-08-30 23:17:49 CEST"
     [5] "2016-06-23 04:49:01 CEST" "2016-09-22 14:37:58 CEST"
     [7] "2015-01-24 17:04:13 CET"  "2015-11-24 07:13:42 CET" 
     [9] "2016-08-29 16:13:13 CEST" "2015-06-06 21:29:18 CEST"
    

    Referencias

    Nube de datos