I would like to create a widget in rshiny
displaying the duration of events using plotly
.
I have a df
with 4 events and their start
ing and end
ing time.
event = c("event_1","event_2","event_3","event_4","event_4","event_2","event_3","event_4","event_4","event_2","event_3","event_4","event_1","event_2","event_3","event_4")
start <- as.POSIXct(c("2019-05-02 07:08:49", "2019-05-02 07:09:21",
"2019-05-02 07:09:41", "2019-05-02 07:10:05",
"2019-05-02 07:24:52", "2019-05-02 07:28:50",
"2019-05-02 07:29:23", "2019-05-02 07:30:16",
"2019-05-02 07:33:13", "2019-05-02 07:33:43",
"2019-05-02 07:35:31", "2019-05-02 07:36:29",
"2019-05-02 07:38:14", "2019-05-02 07:43:26",
"2019-05-02 07:44:59", "2019-05-02 07:53:45"))
stop <- as.POSIXct(c("2019-05-02 07:09:29", "2019-05-02 07:10:02",
"2019-05-02 07:10:17", "2019-05-02 07:10:40",
"2019-05-02 07:29:10", "2019-05-02 07:29:32",
"2019-05-02 07:30:35", "2019-05-02 07:30:53",
"2019-05-02 07:33:48", "2019-05-02 07:34:18",
"2019-05-02 07:36:06", "2019-05-02 07:38:34",
"2019-05-02 07:38:49", "2019-05-02 07:45:19",
"2019-05-02 07:45:35", "2019-05-02 07:54:20"))
df <- data.frame(event = event, start = start, stop = stop)
df
I followed the gantt chart tutorial from here: https://plot.ly/r/gantt/
cols <- RColorBrewer::brewer.pal(length(unique(df$event)), name = "Set3")
df$color <- factor(df$event, labels = cols)
library(plotly)
p <- plot_ly()
for(i in 1:(nrow(df))){
p <- add_trace(p,
x = c(df$start[i], df$stop[i]), # x0, x1
y = c(i, i), # y0, y1
mode = "lines",
line = list(color = df$color[i], width = 20),
hoverinfo = "text",
evaluate = T # needed to avoid lazy loading
)
}
p %>% layout(legend = list(orientation = "h",
xanchor = "center",
x = 0.5))
which gave me this plot1:
but this is not quite what I am after.
What I am after looks like this plot2:
I was able to achieve this using ggplot2
and ggplotly()
but I can't get the x-axes to show minutes after zooming-in. The x-axes is far from detailed.
library(ggplot2)
gp <- ggplot(df, aes(colour = event)) +
geom_segment(aes(x = start, xend = stop , y = event, yend = event), size = 6) +
theme_bw()
ggplotly(gp)
I have two questions, and I should probably divide them into two separate posts although they are workarounds of themselves.
the plotly
way:
How can I have x-axes holding 4 events and y-axes with their corresponding duration? (like in plot2)
the ggplotly()
way:
How can I have more detailed y-axes that displays minutes after zooming in? (like in plot1 - although it is not visible from the .png - the minutes are there)
Thank you in advance!
UPDATE
scale_x_datetime()
, date_format()
gave a detailed xaxis. But now it needs auto hide option.
library(ggplot2)
gp <- ggplot(df, aes(colour = event)) +
geom_segment(aes(x = start, xend = stop , y = event, yend = event), size = 6) +
theme_bw() +
scale_x_datetime(breaks = ("1 min"), labels = scales::date_format("%H:%M"))
ggplotly(gp)