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

时间:2020-05-14 14:11:18

标签: r shiny dygraphs shinyjs r-dygraphs

我的目标是编写一个Shiny应用程序,以可视方式比较多个时间序列。所有时间序列的x值范围都相同。垂直堆叠和同步的笔形图很好地显示了单个时间序列的共同y值的y值。

如果所有图谱都只有一个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)

the x-axis ticks are vertically aligned

在我的用例中,某些图有两个y轴:“ y”和“ y2”。挤压图的x轴和y轴的两倍,为“ y2”轴和标签留出空间:

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)

the x-axis ticks are no longer aligned

问题:

是否有一种方法可以对齐所有笔画的x轴,而不管它们有一个还是两个y轴?

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

  • 为单个变量添加两个y轴
  • 玩dyOptions(rightGap)

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

编辑:错字

1 个答案:

答案 0 :(得分:0)

我使用这段代码来工作(这是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会裁剪其画布,因此当我缩小它们时,它永远不会擦除较宽图形的右侧)< / li>
  • 图例未出现在我展开的图形的正确位置

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