允许绘图在 rmarkdown 中悬垂块文本 html

allow plots to overhang chunk text in rmarkdown html

我正在使用 rmarkdown 准备一些 html 页面,用于在线发布。在显示图表时,我想利用典型计算机显示器上更多可用的宽度(这是我预期目标受众查看我的页面的方式)。 knitr 默认情况下,常规缩放似乎只使用大约 900 像素。

我在this thread中找到了一些css,可以使总的“canvas”变大,这很有帮助。但是,这也会增加所有内容的宽度,包括文本、块回声等,这是我不想要的。我想要的是让我的图形在宽度上“悬垂”于其他元素。增加 fig.widthout.width 并不能做到这一点;这些数字将简单地缩小以适应其他元素使用的相同边界,从而导致更小的字体大小等:

<style type="text/css">
.main-container {
  max-width: 1500px;
  margin-left: auto;
  margin-right: auto;
}
</style>

```{r out.width = "150%", fig.width = 12, fig.height = 3, device = "svg", fig.align='center'}
plot(pressure)
```

这是我想要的那种东西的模型,在 Paint 中拼接在一起:

如您所知,您不应该增加 .main-container 的宽度,而应该增加图像。以下是实现它的一种方法:

---
title: "R Markdown Full-width Figures"
output: html_document
---

```{r out.extra='style="max-width:none; width:100vw; margin-left:calc(50% - 50vw);"', fig.width = 12, fig.height = 3, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
plot(pressure)
```

首先,您需要通过 max-width: none; 删除默认的 max-width 约束(由 rmarkdown 强加)。然后你将图像的宽度设置为 100vw,这意味着 window 的整个宽度。此时,您的图像在 .main-container 内仍然是左对齐的,即它的左侧与 body 元素的其余部分对齐,因此您需要将图像向左移动以使其触及左边距window 的,这就是 margin-left: calc(50% - 50vw) 上面所做的。你可以在一张纸上画一个方框来理解它。基本上,margin-left: 50% 意味着图像将首先向右移动其容器宽度的一半(即 .main-container)。这意味着它的左侧位于容器的中心。由于容器位于页面中央,您需要将图像向左移动 50vw(即 window 宽度的一半)。向左移动意味着给它一个负的左边距,因此 -50vwcalc() 函数动态计算实际像素数,因此您不必为容器假设固定宽度。

一旦您理解了这个 margin-left 技巧,您就可以使用其他可能的宽度,例如 width: 90vw; margin-left: calc(50% - 45vw),它会为您提供宽度为 90vw 并位于页面中央的图像:

如果您不想在 <img> 上内联 CSS,您可以将代码块包装在 fenced Div 中,名称为 class,这样您可以重用为 class 定义的 CSS。这是一个例子:

---
title: "R Markdown Full-width Figures"
output: html_document
---

```{css, echo=FALSE}
.fullwidth img {
  max-width: none;
  width: 100vw;
  margin-left: calc(50% - 50vw);
}
```

## One plot

::: {.fullwidth}
```{r, fig.width = 12, fig.height = 3, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
plot(pressure)
```
:::

## Another plot

::: {.fullwidth}
```{r, fig.width = 12, fig.height = 5, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
boxplot(mpg ~ gear, data = mtcars, horizontal = TRUE)
```
:::