HTML widgets alignment in rmarkdwon

徘徊边缘 提交于 2020-01-15 08:53:32

问题


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
```

回答1:


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
```


来源:https://stackoverflow.com/questions/44458961/html-widgets-alignment-in-rmarkdwon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!