Rmarkdown 自动在绘图上使用函数

Rmarkdown automatically use function on plots

我正在生成一个 RMarkdown 文档,其中每个块都会生成一个图。

对于其中的每一个图,我都想应用一个特殊的格式化函数来调整标题的显示方式。

有没有办法告诉knitr/rmarkdown将这个特殊函数应用到每个块的地块上?例如,也许有一个像 {r, fig.function = adjust_title_position}?

这样的块选项

动机是我不想为每个图分别重新键入函数调用(例如 adjust_title_position(plot_42)),同时,我不想使用 lapply(my_plots, adjust_title_position) 这将需要在一个地方定义所有的地块。

下面是可以应用此功能的 RMarkdown 文件的最小示例。

---
title: "RMD_Example"
output: html_document
---

```{r setup, include=FALSE}
# Load ggplot2
library(ggplot2)

# Define helper function
  adjust_title_position <- function(p) {
    # Shift the horizontal position of the plot title
    p_built <- invisible(ggplot2::ggplot_build(p))
    gt <- invisible(ggplot2::ggplot_gtable(p_built))
    gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))

    # Prints the plot to the current graphical device
      gridExtra::grid.arrange(gt, newpage = TRUE)
    # Invisibly return the gtable object  
      invisible(gt)
  }

```


```{r plot_1}
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg)) +
  labs(title = "Weights and miles-per-gallon")
```

```{r plot_2}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() +
  labs(title = "Sepal length and width")
```

您可以为 ggplot-对象重新注册 print-方法。

# Define helper function
adjusted_title_position <- function(p) {
  # Shift the horizontal position of the plot title
  p_built <- invisible(ggplot2::ggplot_build(p))
  gt <- invisible(ggplot2::ggplot_gtable(p_built))
  gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))

  # Prints the plot to the current graphical device
  gridExtra::grid.arrange(gt, newpage = TRUE)
}

# Reregister print.ggplot
assignInNamespace("print.ggplot", adjusted_title_position, asNamespace("ggplot2"))