使用 shiny 和 ggplot2 交互式绘制多条线

Interactively plotting multiple lines with shiny and ggplot2

我正在创建一个闪亮的应用程序,它将有一个 checkboxGroupInput,其中选中的每个框都会在频率图中添加另一条线。我正在努力思考 reshape2ggplot2 以了解如何实现这一点。

数据:

  head(testSet)
  date store_id product_id count
1 2015-08-15      3       1     8
2 2015-08-15      3       3     1
3 2015-08-17      3       1     7
4 2015-08-17      3       2     3
5 2015-08-17      3       3     1
6 2015-08-18      3       3     2

class等级信息:

dput(droplevels(head(testSet, 10)))
structure(list(date = structure(c(16662, 16662, 16664, 
16664, 16664, 16665, 16665, 16665, 16666, 16666), class = "Date"), 
    store_id = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), product_id = c(1L, 
    3L, 1L, 2L, 3L, 3L, 1L, 2L, 1L, 2L), count = c(8L, 1L, 7L, 
    3L, 1L, 2L, 18L, 1L, 0L, 2L)), .Names = c("date", "store_id", 
"product_id", "count"), row.names = c(NA, 10L), class = "data.frame")

图表应该有一个 x-axis 对应于 date,还有一个 y-axis 对应于 count。我想要一个复选框组输入,其中每个代表选中产品的框,将在图表上绘制对应于 product_id 的线。数据已过滤到 store_id

我的第一个想法是在绘图内编写一个 for 循环,以便为 input$productId 向量的每个返回值呈现一个新的 geom_line()。 - 但是经过一些研究,似乎这是错误的处理方式。

目前我正在尝试 melt() 将数据简化为有用的东西,然后 aes(...group=product_id),但无论我尝试什么都会出错。

正在尝试融化数据:

meltSet <- melt(testSet, id.vars="product_id", value.name="count", variable.name="date")

meltSet 负责人

  head(meltSet)
  product_id date count
1       1 date 16662
2       3 date 16662
3       1 date 16664
4       2 date 16664
5       3 date 16664
6       3 date 16665

meltSet 的尾巴

   tail(meltSet)
   product_id date count
76       9      count     5
77       1      count    19
78       2      count     1
79       3      count    39
80       8      count     1
81       9      count     4

绘图:

ggplot(data=meltSet, aes(x=date, y=count, group = product_id, colour = product_id)) + geom_line()

所以我的轴和值都不稳定,而不是我对设置情节的期望。

如果我理解正确,你不需要任何熔化,你只需要聚合你的数据,按日期和 product_id 汇总计数。为此,您可以使用 data.table:

testSet = data.table(testSet)
aggrSet = testSet[, .(count=sum(count)),  by=.(date, product_id)]

你可以在 aggrSet 上做你的 ggplot 东西。它现在有三列:date, product_id, count.

当你像你一样融化时,你将两个不同类型的变量合并到日期中:date(Date) 和 store_id(int)。