如何将同步 R 绘图的 x 轴与单双 y 轴对齐?

How to align the x-axis of synchronized R dygraphs with single and double y-axis?

我的目标是编写一个闪亮的应用程序来直观地比较多个时间序列。所有时间序列都具有相同的 x 值范围。垂直堆叠和同步的 dygraphs 很好地显示了公共 x 值的各个时间序列的 y 值。

如果所有 dygraphs 只有一个 y 轴(即没有 "y2" 轴),则此方法有效:

library(shiny)
library(dygraphs)

ui <- fluidPage(
  mainPanel(
    dygraphOutput("one_axis"),
    dygraphOutput("two_axis")
  )
)

server <- function(input, output) {
  output$one_axis <- renderDygraph({
    dygraph(fdeaths, group = "foo")
  })
  output$two_axis <- renderDygraph({
    dygraph(mdeaths, group = "foo")
  })
}

shinyApp(ui, server)

在我的用例中,一些 dygraphs 有两个 y 轴:"y" 和 "y2"。具有双 y 轴的图的 x 轴被压扁,使 "y2" 轴和标签成为 space:

library(shiny)
library(dygraphs)

ui <- fluidPage(
  mainPanel(
    dygraphOutput("one_axis"),
    dygraphOutput("two_axis")
  )
)

server <- function(input, output) {
  output$one_axis <- renderDygraph({
    combined <- cbind(mdeaths, fdeaths)
    dygraph(combined, group = "foo") %>% 
      dySeries("mdeaths", axis = "y") %>% 
      dySeries("fdeaths", axis = "y2")
  })
  output$two_axis <- renderDygraph({
    dygraph(mdeaths, group = "foo")
  })
}

shinyApp(ui, server)

问题:

有没有办法对齐所有 dygraphs 的 x 轴,而不管它们是否有一个或两个 y 轴?

我尝试过但没有成功的事情:

我找到了类似的 question,但我不熟悉 javascript。

编辑:打字错误

我使用这段代码(这是 Javascript 但也许 R 中有类似的东西):

// Find our max graph width (finding min doesn't work because dygraph clips its canvases)
var maxWidth = 0;
for (graph of graphs) {
    maxWidth = Math.max(maxWidth, graph.plotter_.area.w);
}
// Use a negative rightGap to make all graphs match the max width
for (graph of graphs) {
    graph.updateOptions({rightGap: graph.plotter_.area.w - maxWidth});
}

我不喜欢它的原因有很多:

  • 它正在使用私有 .plotter_ 变量
  • 它使用负 rightGap 来对齐事物(我尝试使用正 rightGap 将图形缩小到最小尺寸,但我认为 Dygraph 会剪裁其画布,因此当我缩小它们时它不会擦除较宽图形的右侧)
  • 图例没有出现在我展开的图表的正确位置

我使用的是 Dygraph 2.0.0,所以在最新版本中这可能更容易。无论如何,我希望这对您有所帮助 - 我遇到了完全相同的问题,但它暂时解决了我的问题!