Search code examples
rshinydygraphs

dyLegend align left within a shiny-app


I want to place the legend of a dygraph within a shiny app on the left hand side of the plot (within the dygraph). My problem is that I cannot set the absolute width of the dygraph since the app runs at different screens with different resolutions.

The code may be like that:

ui.r:

library(dygraphs)
shinyUI(fluidPage(
  titlePanel("Simple example"),
  sidebarLayout(
    sidebarPanel(),
  mainPanel(
    dygraphOutput("dygraph")
  )
 )
))

server.r

library(dygraphs)
shinyServer(function(input, output, session) {
 output$dygraph <- renderDygraph({
  dygraph(discoveries)
 })
})

Is there a way of getting the width of the dygraph? Or maybe a more simple solution of aligning the legend to the left side?


Solution

  • If you want to align the legend to the top-left then you can use the following CSS:

    .dygraph-legend {
      left: 70px !important;
      background-color: transparent !important;
    } 
    

    You could also easily add this to your code using tableHTML::make_css:

    library(shiny)
    library(tableHTML)
    library(dygraphs)
    ui <- shinyUI(fluidPage(
     tags$style(make_css(list('.dygraph-legend', 
                              c('left', 'background-color'), 
                              c('70px !important', 'transparent !important')))),
     titlePanel("Simple example"),
     sidebarLayout(
      sidebarPanel(),
      mainPanel(
       dygraphOutput("dygraph", width = '80%')
      )
     )
    ))
    
    server <- shinyServer(function(input, output, session) {
     output$dygraph <- renderDygraph({
      lungDeaths <- cbind(mdeaths, fdeaths)
      dygraph(lungDeaths)
     })
    })
    
    shinyApp(ui = ui, server = server)
    

    If you wanted to chage the width of the dygraph container you could use the argument width in dygraphOutput