【问题标题】:HTML widgets alignment in rmarkdwon标记中的 HTML 小部件对齐
【发布时间】:2017-06-09 13:21:27
【问题描述】:

我使用 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
```

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/39562947/…
  • 虽然可能有更好的方法,但我通常使用 CSS 来定位 HTML 小部件。如果您发布示例,我很乐意展示。
  • 已更新示例。

标签: r knitr r-markdown


【解决方案1】:

您可以将绘图调整为文档的默认宽度,然后使用一些 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
```

【讨论】:

  • 感谢您的回答。虽然这解决了我的问题,但我不喜欢我必须在脚本开头添加一些 CSS 代码的事实,而且如果我还有要调整的传单地图,这不是很普遍。你了解styleWidget函数here吗。我希望我可以直接问作者,但我没有足够的声誉来发表评论。
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2018-11-08
  • 2020-10-08
  • 2011-12-15
相关资源
最近更新 更多