我使用 rmarkdown 文档开头的knitr::opts_chunk$set(fig.align = "center")
来设置图形的对齐方式。当我输出 HTML 文件时,静态图形与中心对齐,但 HTML 小部件(例如来自 leaflet()
和ggplotly()
的输出(具有默认对齐方式(向左(。是否有选项可以将 HTML 小部件强制到中心?
编辑:下面给出的示例。
---
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
```
您可以将打印大小调整为文档的默认宽度,然后使用一些 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
```