Centering a dygraph plot in R Markdown

428 Views Asked by At

I'm trying to center a dygraph but it remains left aligned. Below is my minimal example, highlighting how fig.align='center' workings with a normal plot:

---
output: html_document
---

```{r fig.align='center'}
plot(cars)
```

```{r fig.align='center'} 
library(dygraphs)
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths) %>%
dySeries("mdeaths", label = "Male") %>%
dySeries("fdeaths", label = "Female") %>%
dyOptions(stackedGraph = TRUE) %>%
dyRangeSelector(height = 20)
```

enter image description here

How can I make the dygraph center-aligned?

1

There are 1 best solutions below

0
On BEST ANSWER

The dygraph package creates HTML widgets, which behave differently to standard figures in R Markdown which are static images. Based on this answer, we can add some custom CSS to force the HTML widgets to be center-aligned:

---
output: html_document
---

<style>
.html-widget {
    margin: auto;
}
</style>

```{r fig.align='center'} 
library(dygraphs)
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths) %>%
dySeries("mdeaths", label = "Male") %>%
dySeries("fdeaths", label = "Female") %>%
dyOptions(stackedGraph = TRUE) %>%
dyRangeSelector(height = 20)
```

enter image description here