13.2 Overlayed
13.2.1 Goal
Create a plot of all data per week by season of the year:
13.2.2 Data Basis
Energy consumption values of one whole year in an interval of 15mins.
13.2.3 Solution
Create a new script, copy/paste the following code and run it:
# change language to English, otherwise weekdays are in local language
Sys.setlocale("LC_TIME", "English")
## [1] "English_United States.1252"
library(plotly)
library(dplyr)
library(lubridate)
# load time series data
df <- readRDS(system.file("sampleData/eboBookEleMeter.rds", package = "redutils"))
df <- dplyr::mutate(df, value = value * 4)
# add metadata for later grouping and visualization purposes
df$x <- hour(df$timestamp) + minute(df$timestamp)/60 + second(df$timestamp) / 3600
df$weekday <- weekdays(df$timestamp)
df$weekday <- factor(df$weekday, c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday", "Sunday"))
df$day <- as.Date(df$timestamp, format = "%Y-%m-%d %H:%M:%S")
df <- df %>% dplyr::mutate(value = ifelse(x == 0.00, NA, df$value))
# plot graph with all time series
rangeX <- seq(0,24,0.25)
maxValue <- max(df$value, na.rm = TRUE)*1.05
plot <- df %>%
highlight_key(~day) %>%
plot_ly(x=~x,
y=~value,
color=~weekday,
type="scatter",
mode="lines",
line = list(width = 1),
alpha = 0.15,
colors = "dodgerblue4",
text = ~day,
hovertemplate = paste("Time: ", format(df$timestamp, "%H:%M"),
"<br>Date: ", format(df$timestamp, "%Y-%m-%d"),
"<br>Value: %{y:.0f}")) %>%
# workaround with add_trace to have fixed y axis when selecting a dedicated day
add_trace(x = 0, y = 0, type = "scatter", showlegend = FALSE, opacity=0) %>%
add_trace(x = 24, y = maxValue, type = "scatter", showlegend = FALSE, opacity=0) %>%
layout(title = "Daily Profiles - Overlayed",
showlegend = TRUE,
xaxis = list(
title = "Hour of day",
range = rangeX,
tickvals = list(0, 3, 6, 9, 12, 15, 18, 21),
showline=TRUE
),
yaxis = list(
title = "Power (kW)",
range = c(0, maxValue)
)
) %>%
highlight(on = "plotly_hover",
off = "plotly_doubleclick",
color = "orange",
opacityDim = 1.0,
selected = attrs_selected(showlegend = FALSE)) %>% # this hides elements in the legend
plotly::config(modeBarButtons = list(list("toImage")), displaylogo = FALSE)
# show plot
plot