2

I use the knitr::opts_chunk$set(fig.align = "center") at the beginning of the rmarkdown document to set the alignment of figures. When I output HTML files, the static figures are aligned to the center, but the HTML widgets, such as outputs from leaflet() and ggplotly() have the default alignment (to the left). Is there an option to force the HTML widgets to the center?

EDIT: example given below.

---
title: "test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.align = "center")
library(ggplot2)
library(plotly)
```

```{r static plot}
# This is aligned to center

g <- ggplot(mtcars, aes(mpg, cyl)) + 
geom_point()
g
```

```{r html widget}
# html output isn't aligned
p <- ggplotly(g)
p
```
moho wu
  • 471
  • 4
  • 13

1 Answers1

0

You could resize the plot to the default width of the document and then use some CSS:

---
title: "Untitled"
output: html_document
---

<style>
/* resize the widget container */
.plotly { 
  width: 100% !important;
}

/* center the widget */
div.svg-container {
  margin: auto !important;
}
</style>

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.align = "center")
library(ggplot2)
library(plotly)
```


```{r static plot}
# This is aligned to center
g <- ggplot(mtcars, aes(mpg, cyl)) + 
geom_point()
g
```

```{r html widget}
p <- ggplotly(g, browser.fill = F) %>% 
  layout(autosize = F, width = '100%', height = '100%')
p
```
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • Thanks for your answer. While this solves my problem, I don't like the fact that I have to add some CSS codes at the beginning of the script and it's not very generalisable if I also have a leaflet map I want to adjust. Do you understand the `styleWidget` function [here](https://stackoverflow.com/a/39607828/4227151). I wish I could ask the author directly, but I don't have enough reputation to comment. – moho wu Jun 12 '17 at 15:29