Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying multiple dygraphs on a grid in R-Markdown

Following the conversation here, is there a way to organize the output dygraphs in a grid? To Have one or more graph in a row.

The code below would generate 4 dygraphs arranged vertically. Is there a way to organize them in a 4x4 grid?

I tried using tags$div but it wraps all the graphs in one div. Is there a way to apply a CSS property such as display: inline-block; to each dygraph widget? or any other better method?

```{r}
library(dygraphs)
library(htmltools)


makeGraphs = function(i){
  dygraph(lungDeaths[, i], width = 300, height = 300, group = "lung-deaths")%>%
    dyOptions(strokeWidth = 3) %>%
    dyRangeSelector(height = 20)
}


lungDeaths <- cbind(mdeaths, fdeaths, ldeaths, mdeaths)
res <- lapply(1:4, makeGraphs )
htmltools::tagList(tags$div(res, style = "width: 620px; padding: 1em; border: solid; background-color:#e9e9e9"))
```

Current output screenshot:

enter image description here

like image 378
yurikleb Avatar asked Jun 24 '18 06:06

yurikleb


People also ask

How do I plot side by side in R markdown?

To place multiple figures side-by-side from the same code chunk, you can use the fig. show='hold' option along with the out. width option. Figure 2.5 shows an example with two plots, each with a width of 50% .

How do I show plots in R markdown?

In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.

What are Dygraphs?

dygraphs is a fast, flexible open source JavaScript charting library. It allows users to explore and interpret dense data sets.


1 Answers

I think I figured it out, not sure its the best solution, but adding a wrapper div with a display:inline-block; property seems to work quite well.

I just added this line to the function that generates each dygraph:

htmltools::tags$div(theGraph, style = "padding:10px; width: 250px; border: solid; background-color:#e9e9e9; display:inline-block;")

so the updated code looks like this:

```{r graphs}
library(dygraphs)
library(htmltools)


makeGraphs = function(i){
  theGraph <- dygraph(lungDeaths[, i], width = 400, height = 300, group = "lung-deaths")%>%
    dyOptions(strokeWidth = 3) %>%
    dyRangeSelector(height = 20)

  htmltools::tags$div(theGraph, style = "padding:10px; width: 450px; border: solid; background-color:#e9e9e9; display:inline-block;")

}



lungDeaths <- cbind(mdeaths, fdeaths, ldeaths, mdeaths)
res <- lapply(1:4, makeGraphs )
htmltools::tagList(res) 

```

Output Screenshot: enter image description here

like image 118
yurikleb Avatar answered Sep 28 '22 23:09

yurikleb