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

后端 未结 1 607
天命终不由人
天命终不由人 2021-01-01 07:05

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

相关标签:
1条回答
  • 2021-01-01 07:42

    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 shiny context of course, but not in rstudio.

    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 dygraphs 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)
    
    0 讨论(0)
提交回复
热议问题