这个问题与For loop over dygraph 在 R 中不起作用有关
@Yihui 的这个答案很好地详细说明了如何在 rmarkdown 的循环中创建 dygraphs 图。但是,正如您会注意到的,图之间没有间距。当它们有很多时,这变得非常难以阅读。
```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
res <- lapply(1:2, function(i) dygraph(lungDeaths[, i]))
htmltools::tagList(res)
```
有没有办法在自定义应用功能本身内生成的每个图之间添加间距、文本、水平规则等?
我目前的解决方法是传入一个 dyOptions titleHeight 参数,以及一个指向外部 CSS 的 dyCSS 参数,该外部 CSS 在标题顶部设置填充。例如,我可以将 titleHeight 参数设置为 50px,然后将标题本身设置为 25px,顶部填充高度为 25px。
---
title: "test"
author: "test"
date: "test"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
res <- lapply(1:2, function(i) {
dygraph(lungDeaths[, i], main = "Lung Deaths") %>%
dyOptions(titleHeight = 50) %>%
dyCSS("dygraph.css")
})
htmltools::tagList(res)
```
和 dygraphs.css 文件:
.dygraph-title {
font-size: 25px;
padding-top: 25px;
}
如果我不想要情节标题,但仍想要情节之间的分隔,我将换行符作为标题传递,如下所示:
```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
res <- lapply(1:2, function(i) {
dygraph(lungDeaths[, i], main = "<br>") %>%
dyOptions(titleHeight = 50) %>%
dyCSS("dygraph.css")
})
htmltools::tagList(res)
```
虽然这确实可以增加间距,但如果可能的话,我宁愿避免使用外部 CSS。更不用说,它不允许您在绘图本身之间添加任何其他对象(如文本或水平规则)。有没有办法在函数调用的每次迭代之间手动添加这些对象?
编辑:因此,根据下面的答案,我们还可以在每次迭代之间添加一个中断,如下所示:
```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
res <- lapply(1:2, function(i) {
dygraph(lungDeaths[, i])
})
invisible(lapply(1:2, function(i) {
if (!exists("l")) {
l <<- list()
}
l[[i]] <<- htmltools::tags$br()
}))
out <- c(rbind(l, res))
htmltools::tagList(out)
```
这看起来不错,尽管我很想听听其他想法。