从普通条形图移动到图上的堆叠条形图

ale*_*c22 6 r xts dygraphs

我有以下格式的 xts df:

structure(c("May 2022", "Jun 2022", "Jul 2022", "Aug 2022", "Sep 2022", 
"Oct 2022", "Nov 2022", "Dec 2022", " 3035.199", " 5500.000", 
"11568.750", " 2510.000", " 6999.999", "21792.149", " 9750.000", 
" 5624.999", " 2250.000", " 4136.975", " 6525.500", " 2771.875", 
" 4637.500", "16273.499", " 6000.000", " 4494.649", " 2500.000", 
"    0.000", " 3029.000", " 2803.500", "    0.000", "14481.250", 
" 4374.998", " 4062.498", "    0.000", " 3075.000", " 6939.249", 
" 1500.000", " 4183.157", " 5769.000", " 3559.500", " 3250.000"
), class = c("xts", "zoo"), index = structure(c(1651363200, 1654041600, 
1656633600, 1659312000, 1661990400, 1664582400, 1667260800, 1669852800
), tzone = "UTC", tclass = "yearmon"), .Dim = c(8L, 5L), .Dimnames = list(
    NULL, c("Month", "Cat 1", "Cat 2", "Cat 3", "Cat 4")))
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 dygraphs 库创建一个堆积条形图。

library(dygraphs)
library(lubridate)
today <- as.Date(Sys.time())
    last_6 <- today+months(-6)
        dygraph(df) %>%
          dyAxis("y", label= "Total") %>%
          dyRangeSelector(dateWindow = c(last_6, today)) %>%
          dyMultiColumnGroup(c("Cat 1", "Cat 2", "Cat 3", "Cat 4"))
Run Code Online (Sandbox Code Playgroud)

这会生成一个如下所示的条形图:当前条形图

我想知道是否有人对如何制作堆积条形图有任何建议?许多指南都谈到引入绘图仪,但不幸的是,它们不够详细,无法让我正确理解正在发生的事情。

添加这个:

dyStackedBarGroup(c("Cat 1", "Cat 2", "Cat 3", "Cat 4"))
Run Code Online (Sandbox Code Playgroud)

而不是 dyMultiColumnGroup 行导致:

Error in cumulativeYval + points : non-numeric argument to binary operator
Run Code Online (Sandbox Code Playgroud)

Kat*_*Kat 4

虽然昆顿给出了一个很好的可行答案,但我想我会补充一下。

你不需要单独的ts对象;不过,您确实需要数据是数字的。

假设来自的数据dput名为df

# drop the months column, change data to numeric, restore ts class
df <- df[ ,-1] %>% sapply(as.numeric) %>%
  ts(start = c(2022, 5), deltat = 1/12)
Run Code Online (Sandbox Code Playgroud)

现在您已准备好绘制图表了。

dygraph(df) %>%
  dyAxis("y", label= "Total") %>%
  dyRangeSelector(dateWindow = c(today() - months(6), today())) %>%
  dyStackedBarGroup(dimnames(df)[[2]])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述