我有以下简单的 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轴应对应于所用时间,条形应为用户堆栈 .
在剧情中做这种条形图的典型方法似乎是这样的
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
)))
2 回答
首先,您的
user
列是出于某种原因的列表,所以让我们解决这个问题:现在,我从未使用过
plotly
,所以我不知道结果应该是什么,但这会复制你所描述的你想做的事情:不幸的是,其他答案没有用 . 最简单的解决方案是使用
ggplot2
创建堆积条形图,然后使用plotly
转换它:(ggplot(data = dt, aes(date, time, fill=user)) + geom_bar(stat="identity")) %>% ggplotly()