【发布时间】:2019-08-27 13:54:29
【问题描述】:
我想在rshiny 中创建一个小部件,使用plotly 显示事件的持续时间。
我有一个 df 有 4 个事件及其 starting 和 ending 时间。
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
我从这里开始学习甘特图教程: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))
我可以使用ggplot2 和ggplotly() 来实现这一点,但我无法让x 轴在放大后显示几分钟。 x轴远非详细。
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)
我有两个问题,我可能应该将它们分成两个单独的帖子,尽管它们本身就是解决方法。
plotly 方式:
如何让 x 轴保持 4 个事件和 y 轴及其相应的持续时间? (如情节2)
ggplotly() 方式:
如何在放大后显示更详细的 y 轴? (就像在 plot1 中一样 - 虽然从 .png 中看不到它 - 分钟在那里)
提前谢谢你!
更新scale_x_datetime(), date_format() 给出了详细的 xaxis。但现在它需要自动隐藏选项。
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)
【问题讨论】:
标签: r ggplot2 plotly r-plotly ggplotly