首页 文章

系列突出了R / Shiny的dygraphs包中的传奇

提问于
浏览
1

我在R中编写了一个Shiny应用程序,它使用了dygraphs包 .

该应用程序具有交互式绘图,使用 dyHighlight() 功能突出显示所选系列 . 但是,由于数据涉及1000列,因此图例显示1000系列 .

这是一个只有2列的最小代码示例:

ui <- fluidPage(

  # This CSS code should solve the problem, but somehow does not.
  # To test, replace CSS in tags$style(...) with this code
  #.dygraph-legend  { display: none; }
  #.dygraph-legend .highlight { display: inline; }

  # CSS to highlight selected series in legend.
  # Does not solve problem, but is best alternative for now.
  tags$style("
              .highlight {
               border: 2px solid black;
               background-color: #B0B0B0;
              }

             "), 

  sidebarLayout(

    sidebarPanel(),

    mainPanel(dygraphOutput("plot"))

  )

)

server <- function(input, output) {

  set.seed(123)
  data <- matrix(rnorm(12), ncol = 2)
  data <- ts(data)

  # Workaround for what might be a bug
  # Reference: https://stackoverflow.com/questions/28305610/use-dygraph-for-r-to-plot-xts-time-series-by-year-only
  data <- cbind(as.xts(data[,1]), as.xts(data[,2]))

  colnames(data) <- c("Series 1", "Series 2")
  #print(data) # Uncomment to view data frame

  output$plot <- renderDygraph({

    dygraph(data) %>%

      # Highlighting series
      dyHighlight(data, 
                  highlightCircleSize = 2, 
                  highlightSeriesBackgroundAlpha = .5, 
                  highlightSeriesOpts = list(strokeWidth = 2))

  })

}

shinyApp(ui = ui, server = server)

有没有办法调整R / Shiny中的图例,以便只显示突出显示的系列(而不是同一时间点的所有系列)?
以下链接中较低的2个图显示了应该实现的目标:http://dygraphs.com/gallery/#g/highlighted-series

这已经在stackoverflow上多次受到质疑,但尚未得到回答或不起作用(我不想发布necro帖子):
Is there a way to highlight closest series in R dygraphs?
Highlight Closest Series - but only show X/Y of highlighted series?
100 labels in separate div with highlighted series in a box

无论如何, dyHighlight() 似乎没有支持此功能的内置参数,因此可能需要JavaScript和CSS .

搜索互联网让我从以下链接 highlightSeriesOptshighlightCallbackunhighlightCallbackhttp://dygraphs.com/options.html

但是你如何在R中使用这些选项?

1 回答

  • 2

    这应该让你开始:

    https://rstudio.github.io/dygraphs/gallery-css-styling.html

    http://dygraphs.com/css.html

    图例中有.dygraph-legend类 . 使用highlightSeriesOpts时,所选系列'获得.highlight类 . 这可用于仅显示图例中的单个系列 .

    所以你必须创建CSS文件并将其添加到grapgh:https://rstudio.github.io/dygraphs/gallery-css-styling.html

    这应该有效,但由于某种原因 .dygraph-legend 正在接管并且没有显示任何图例 .

    .dygraph-legend  { display: none; }
    
    .highlight {
      display: inline;
    }
    

    Altenative:

    .dygraph-legend  { display: all; }
    
    .highlight {
      display: inline;
      background-color: #B0B0B0;
    }
    

    将其另存为* .css文件:

    dygraph(data)%>% dyHighlight() %>% dyCSS("path to css")
    

    这不能解决问题,但会为所选系列添加一个亮点:
    enter image description here

相关问题