【问题标题】:How to align the x-axis of synchronized R dygraphs with single and double y-axis?如何将同步 R dygraphs 的 x 轴与单双 y 轴对齐?
【发布时间】:2020-08-31 02:45:14
【问题描述】:

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

如果所有 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”轴和标签腾出空间:

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 轴?

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

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

我发现了一个类似的question,但我不熟悉 javascript。

编辑:错字

【问题讨论】:

    标签: r shiny dygraphs shinyjs r-dygraphs


    【解决方案1】:

    我使用这段代码得到了这个工作(这是 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,所以在最新版本中这可能更容易。无论如何,我希望这会有所帮助 - 我遇到了完全相同的问题,现在它让我解决了!

    【讨论】:

    • 您好,非常感谢您抽出宝贵时间分享您的解决方案。您的解决方案是在 javascript 中,对吗?我不太明白如何在 R 中工作(例如在上面的示例中)。您是否在 R 脚本中启动并运行它?
    • 对不起,我应该提一下 - 它确实是 Javascript。我从来没有使用过 R,所以我在那里帮不上忙,但希望这至少有一些提示,可能会以某种方式转化为 R。
    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多