Search code examples
htmlrplotlyr-markdown

How to properly fit plotly graphs in RMarkdown html documents?


I am trying to include plotly graphs produced by timetk functions in rmarkdown html notebook but I am not sure why these plots shrink in width in the html document whereas they appear fine in rmardown source editor.

To adjust the plots I have changed the chunk options to:

{r, out.width= "100%"}

knitr::opts_chunk$set(echo = TRUE, mmessage = FALSE, warning = FALSE,
                      fig.width=12)

When I generate the html document I have noticed couple of issues with plotly graphs not fitting properly (in width) in the html document

1) Graph is not spread to 100 % of the width as the document chunks size

Left Side of image is from rmarkdown source editor, Right Side is from html notebook

enter image description here

2) the legend overlaps the graph.

Left Side of image is from rmarkdown source editor (correct plot), Right Side is from html notebook (overlapping legend)

enter image description here

How do I fix these issues ?

Appreciate any help here!!


Solution

  • You can try disabling autosize and setting the width manually with layout.

    x <- c(1:100)
    random_y <- rnorm(100, mean = 0)
    dd <- data.frame(x, random_y)
    
    fig <- plot_ly(dd, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines') %>% 
      layout(autosize = F, width = 900, height = 500)
    
    fig