使用 data.table 和 plotly 的堆积条形图

Stacked bar chart using data.table and plotly

我有以下简单的data.table

          date     user              time
 1: 2016-04-25 3533f254   2.21666667 secs
 2: 2016-05-02 e627fa24   1.45833333 secs
 3: 2016-05-02 451872fe   5.08333333 secs
 4: 2016-05-02 105826aa  42.75000000 secs
 5: 2016-05-02 9a527a36 122.78333333 secs
 6: 2016-05-09 451872fe  89.82500000 secs
 7: 2016-05-09 9a527a36   3.06000000 secs
 8: 2016-05-09 cbbc1b3a   0.03014352 secs
 9: 2016-05-16 451872fe   0.55000000 secs
10: 2016-05-16 9a527a36   0.45000000 secs

如何使用 plotly(可能使用 data.table- 或 plotly- 特定功能)创建这种 data.table 的堆积条形图?实际数据有更多行的日期、用户和时间。 x 轴应对应于日期,y 轴应对应于所用时间,条形图应为用户堆栈。

在 plotly 中制作这种条形图的典型方法似乎类似于

p1 <- plot_ly(x = x1, y = y1, type = "bar")
p2 <- add_trace(p1, x = x2, y = y2)
p3 <- add_trace(p2, x = x3, y = y3)
p4 <- layout(p3, barmode = "stack")
p4

但在这种情况下,由于数据的行数,手动指定每个 x,y 组是不可行的。

示例输入:

dt <- as.data.table(structure(list(date = structure(c(1L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 4L, 4L), .Label = c("2016-04-25", "2016-05-02", "2016-05-09", 
"2016-05-16", "2016-05-23", "2016-05-30", "2016-06-06", "2016-06-13", 
"2016-06-20", "2016-06-27", "2016-07-04", "2016-07-11", "2016-07-18", 
"2016-07-25", "2016-08-01", "2016-08-08", "2016-08-15", "2016-08-22", 
"2016-08-29"), class = "factor"), user = list("3533f254", "e627fa24", 
    "451872fe", "105826aa", "9a527a36", "451872fe", "9a527a36", 
    "cbbc1b3a", "451872fe", "9a527a36"), time = structure(c(2.21666666666667, 
1.45833333333333, 5.08333333333333, 42.75, 122.783333333333, 
89.825, 3.06, 0.0301435185185185, 0.55, 0.45), units = "secs", class = "difftime")), .Names = c("date", 
"user", "time"), class = "data.frame", row.names = c(NA, -10L
)))

首先,出于某种原因,您的 user 列是一个列表,所以让我们解决这个问题:

dt[, user := unlist(user)]

现在,我从未使用过 plotly,所以我不知道结果 应该 是什么,但这将复制您想要描述的内容要做:

dt[, {if (.GRP == 1)
        plot_ly(x = date, y = time, type = 'bar')
      else
        add_trace(x = date, y = time)
     }, by = user]

layout(barmode = "stack")

很遗憾,其他答案无效。最简单的解决方案是使用 ggplot2 创建堆叠条形图,然后使用 plotly:

进行转换

(ggplot(data = dt, aes(date, time, fill=user)) + geom_bar(stat="identity")) %>% ggplotly()