Search code examples
rdygraphs

Is there a way to add legend next to a dygraph in R, not exactly on the plot?


I'vw plotted a dygraph using a dygraph function from a dygraphs R package. I wonder is there a way to put legend next to the plot, not exactly on it like it is done by default...

Code to reproduce this dygraph is below:

library(archivist)
library(dplyr)
library(devtools)
devtools::install_github("rstudio/dygraphs")
library(dygraphs)
seriesReactive <- loadFromGithubRepo( "db914a43536d4d3f00cf3df8bf236b4a", user= "MarcinKosinski", repo="Museum", value = TRUE)
dygraph(seriesReactive, main = "Dzienna proporcja kliknięć do odsłon dla danych struktur", ylab = "Proporcja") %>% 
    dyRangeSelector()

enter image description here


Solution

  • Yes, read ?dygraphs::dyLegend. The description of labelsDiv argument says:

    Show data labels in an external div, rather than on the graph. This value should be a div element id.

    This is easy to do in a context of course, but not in .

    For instance, in Shiny ui.R file, I have added this line:

    box(title = "Legend", textOutput("legendDivID"))
    

    Which creates an HTML <div> tag with the ID legendDivID. Then, in Shiny server.R file, I use the same ID in params:

    dygraph(...) %>% dyLegend(labelsDiv = "legendDivID")
    

    And it works like a charm.

    In your case, here is the result:

    enter image description here

    And the code (just create app.R script in RStudio and run it by calling shiny::runApp()):

    ## app.R ##
    library(shinydashboard)
    library(shiny)
    library(dygraphs)
    
    ui <- dashboardPage(
      dashboardHeader(title = "Page title"),
      dashboardSidebar(sidebarMenu(menuItem("tab title", tabName = "tab", icon = icon("globe")))),
      dashboardBody(
        tabItems(
          tabItem(tabName = "tab",
                  fluidRow(
                      box(dygraphOutput("graph"), width=9),
                      box(textOutput("legendDivID"), title = "Legend", collapsible = TRUE, width=3)
                    )
          )
        )
      )
    )
    
    server <- function(input, output) {
      library(archivist)
      library(dplyr)
      seriesReactive <- loadFromGithubRepo( "db914a43536d4d3f00cf3df8bf236b4a", user= "MarcinKosinski", repo="Museum", value = TRUE)
    
      output$graph <- renderDygraph({
        withProgress(message = "Loading...", {
          dygraph(seriesReactive, main = "Dzienna proporcja kliknięć do odsłon dla danych struktur", ylab = "Proporcja") %>% 
            dyRangeSelector() %>%
            dyLegend(labelsDiv = "legendDivID")
        })
      })
    }
    
    shinyApp(ui, server)